package com.crm.system.service.impl.returnMoney;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.*;
import com.crm.model.dto.InsertReturnMoneyCallable;
import com.crm.model.dto.SalesmanDto;
import com.crm.model.entity.MessageManager.Message;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.contractManager.CustomerContractDeveloper;
import com.crm.model.entity.customerManager.*;
import com.crm.model.entity.finishOrderProduct.FinishOrderProduct;
import com.crm.model.entity.orderManager.CustomerOrderInvoice;
import com.crm.model.entity.orderManager.CustomerProductOrder;
import com.crm.model.entity.report.ReportPerformanceTop;
import com.crm.model.entity.returnMoney.ModifyRoyaltyStatus;
import com.crm.model.entity.returnMoney.ReturnMoney;
import com.crm.model.entity.returnMoney.ReturnMoneyLog;
import com.crm.model.entity.sys.ImportFailureLog;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.qo.messageManager.MessageAddQO;
import com.crm.model.qo.productManager.AnalyseReturnMoneyProductQO;
import com.crm.model.qo.returnMoney.ReturnMoneyQO;
import com.crm.model.vo.customerContractManager.CustomerContractDetailVO;
import com.crm.model.vo.customerContractManager.CustomerContractVO;
import com.crm.model.vo.customerManager.*;
import com.crm.model.vo.finishOrderProduct.FinishOrderProductVO;
import com.crm.model.vo.orderManager.CustomerProductOrderVO;
import com.crm.model.vo.orderManager.ImportOrderNumber;
import com.crm.model.vo.orderManager.OrderActivityVO;
import com.crm.model.vo.orderManager.PerformanceRankVO;
import com.crm.model.vo.productManager.AnalyseReturnMoneyProductVO;
import com.crm.model.vo.productManager.PerformanceAnalysisVO;
import com.crm.model.vo.productManager.ProductVO;
import com.crm.model.vo.productManager.ShelfProductsVO;
import com.crm.model.vo.returnMoney.*;
import com.crm.model.vo.sys.ImportFailureLogVO;
import com.crm.redis.RedisPrefix;
import com.crm.redis.mapper.ValueRMapper;
import com.crm.redis.service.returnMoneyManager.ReturnMoneyRedisService;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.contractManager.CustomerContractDeveloperDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.finishOrderProductManager.FinishOrderProductDbService;
import com.crm.service.messageprompt.MessagePromptDbService;
import com.crm.service.orderManager.CustomerOrderInvoiceDbService;
import com.crm.service.orderManager.CustomerProductOrderDbService;
import com.crm.service.orderManager.CustomerProductOrderDetailDbService;
import com.crm.service.productManager.CustomerMemberProductDbService;
import com.crm.service.productManager.CustomerProductDbService;
import com.crm.service.report.ReportPerformanceTopDbservice;
import com.crm.service.returnMoney.*;
import com.crm.service.sendRoyaltyManager.SendRoyaltyDbService;
import com.crm.service.sys.ImportFailureLogDbService;
import com.crm.service.sys.UserAccountDbService;
import com.crm.service.sys.permissionManagement.SysCompanyDbService;
import com.crm.service.taskManager.TaskReturnMoneyFlagDbService;
import com.crm.system.service.customerManager.CustomerService;
import com.crm.system.service.impl.csd.customerManager.CustomerServiceImpl;
import com.crm.system.service.messageManager.MessageService;
import com.crm.system.service.orderManager.CustomerProductOrderService;
import com.crm.system.service.returnMoney.ReturnMoneyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReturnMoneyServiceImpl implements ReturnMoneyService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ReturnMoneyDbservice returnMoneyDbservice;

    @Autowired
    private CustomerProductOrderDbService productOrderDbService;

    @Autowired
    private CustomerContractDbService contractDbService;

    @Autowired
    private FinishOrderDBservice finishOrderDBservice;

    @Autowired
    private ReturnMoneyLogDbService returnMoneyLogDbService;

    @Autowired
    private CustomerDbService customerDbService;

    @Autowired
    private MessagePromptDbService messagePromptDbService;

    @Autowired
    private UserAccountDbService userAccountDbService;

    @Autowired
    private ImportFailureLogDbService importFailureLogDbService;

    @Autowired
    private SysCompanyDbService companyDbService;

    @Autowired
    private SendRoyaltyDbService sendRoyaltyDbService;

    @Autowired
    private CustomerProductOrderDetailDbService customerProductOrderDetailDbService;

    @Autowired
    private FinishOrderProductDbService finishOrderProductDbService;

    @Autowired
    private CustomerMemberProductDbService customerMemberProductDbService;

    @Autowired
    private SysCompanyDbService sysCompanyDbService;

    @Autowired
    private ReturnMoneyRedisService returnMoneyRedisService;

    @Autowired
    private CustomerContractDbService customerContractDbService;

    @Autowired
    private CustomerProductOrderService customerProductOrderService;

    @Autowired
    private CustomerProductOrderDbService customerProductOrderDbService;

    @Autowired
    private CustomerContractDeveloperDbService customerContractDeveloperDbService;

    @Autowired
    private CustomerOrderInvoiceDbService customerOrderInvoiceDbService;

    @Autowired
    private CustomerServiceImpl csdCustomerServiceImpl;

    @Autowired
    private ReportPerformanceTopDbservice reportPerformanceTopDbservice;

    @Autowired
    private TaskReturnMoneyFlagDbService taskReturnMoneyFlagDbService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ModifyRoyaltyStatusDbService modifyRoyaltyStatusDbService;

    @Autowired
    private ModifyRoyaltyStatusLogDbService modifyRoyaltyStatusLogDbService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private CustomerProductDbService customerProductDbService;

    @Autowired
    private CustomerService customerService;

    /**
     * 销售员每月业绩存入redis的key
     */
    final String SALESMAN_REDIS_KEY="salesman_month_results";

    @Override
    public DhPageInfo<ReturnMoneyVO> selectCustomerProductList(ReturnMoneyQO returnMoneyQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        //4是分公司财务 3是总部财务
        if ("4".equals(userAccount.getDeptId())){
            returnMoneyQO.setCompanyId(userAccount.getCompanyId());
        }

        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "createTm":
                {
                    order.append("create_tm ").append(sortOrder);//创建时间
                }
                break;
                case "arriveTime":
                {
                    order.append("arrive_time ").append(sortOrder);//创建时间
                }
                break;
                case "arriveMoney":
                {
                    order.append("arrive_money ").append(sortOrder);//创建时间
                }
                break;
                case "arriveUnitName":
                {
                    order.append("arrive_unit_name ").append(sortOrder);//创建时间
                }
                break;
                case "arriveNum":
                {
                    order.append("arrive_num ").append(sortOrder);//创建时间
                }
                break;
                case "arriveMethod":
                {
                    order.append("arrive_method ").append(sortOrder);//创建时间
                }
                break;
                case "arriveIsAbolish":
                {
                    order.append("arrive_is_abolish ").append(sortOrder);//创建时间
                }
                break;
                case "paymentUnitName":
                {
                    order.append("payment_unit ").append(sortOrder);//创建时间
                }
                break;
                case "paymentAccount":
                {
                    order.append("payment_account ").append(sortOrder);
                }
                break;
                case "contractStatus":
                {
                    order.append("contract_status ").append(sortOrder);
                }
                break;
                case "renewContractStartTime":
                {
                    order.append("renew_contract_start_time ").append(sortOrder);
                }
                break;
                case "scoreConvertRatio":
                {
                    order.append("score_convert_ratio ").append(sortOrder);
                }
                break;
                case "scoreMoney":
                {
                    order.append("score_money ").append(sortOrder);
                }
                break;
                case "vipType":
                {
                    order.append("vip_type ").append(sortOrder);
                }
                break;
                case "isRecordScore":
                {
                    order.append("is_record_score ").append(sortOrder);
                }
                break;
                case "isBack":
                {
                    order.append("is_back ").append(sortOrder);
                }
                break;
                case "backDate":
                {
                    order.append("back_date ").append(sortOrder);
                }
                break;
                case "royaltyStatus":
                {
                    order.append("royalty_status ").append(sortOrder);
                }
                break;
                case "royaltyMoney":
                {
                    order.append("royalty_money ").append(sortOrder);
                }
                break;
                case "royaltyRecordTime":
                {
                    order.append("royalty_record_time ").append(sortOrder);
                }
                break;
                case "isAbolish":
                {
                    order.append("is_abolish ").append(sortOrder);
                }
                break;
                case "source":
                {
                    order.append("source ").append(sortOrder);
                }
                break;
                case "contractId":
                {
                    order.append("contract_id ").append(sortOrder);
                }
                break;
                case "customerName":
                {
                    order.append("customer_id ").append(sortOrder);
                }
                break;
                case "orderId":
                {
                    order.append("order_id ").append(sortOrder);
                }
                break;
                case "salesmanName":
                {
                    order.append("salesman_id ").append(sortOrder);
                }
                break;
                case "filialeName":
                {
                    order.append("filiale_id ").append(sortOrder);
                }
                break;
                case "isCheck":
                {
                    order.append("is_check ").append(sortOrder);
                }
                break;
                case "remark":
                {
                    order.append("remark ").append(sortOrder);
                }
                break;
                case "createByName":
                {
                    order.append("create_by ").append(sortOrder);
                }
                break;
                case "updateByName":
                {
                    order.append("update_by ").append(sortOrder);
                }
                break;
                case "updateTm":
                {
                    order.append("update_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(returnMoneyQO.getDateType())) {
            if ("week".equals(returnMoneyQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("month".equals(returnMoneyQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("year".equals(returnMoneyQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
            if ("topDay".equals(returnMoneyQO.getDateType())) {
                //昨天
                dateUnit = 4;
            }
            if ("day".equals(returnMoneyQO.getDateType())) {
                //今天
                dateUnit = 5;
            }
//            if ("all".equals(returnMoneyQO.getDateType())){
//                //全部
//                dateUnit = 0;
//            }
            if("lastMonth".equals(returnMoneyQO.getDateType())){
                //上月
                dateUnit = 6;
            }
        }
        List<ReturnMoneyVO> returnMoneyVOList= returnMoneyDbservice.selectCustomerProductList(returnMoneyQO,order.toString(),dateUnit);
        PageInfo<ReturnMoneyVO> pageInfo = new PageInfo<ReturnMoneyVO>(returnMoneyVOList);
        return new DhPageInfo<ReturnMoneyVO>(pageInfo, returnMoneyVOList);
    }

    /**
     * 分公司财务统计回款列表
     * @param returnMoneyQO
     * @param pageIndex
     * @param pageSize
     * @param sortName
     * @param sortOrder
     * @return
     */
    @Override
    public DhPageInfo<ReturnMoneyVO> selectStatReturnMoney(ReturnMoneyQO returnMoneyQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(returnMoneyQO.getDateType())) {
            if ("thisWeek".equals(returnMoneyQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(returnMoneyQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(returnMoneyQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
            if ("topDay".equals(returnMoneyQO.getDateType())) {
                //昨天
                dateUnit = 4;
            }
            if ("day".equals(returnMoneyQO.getDateType())) {
                //今天
                dateUnit = 5;
            }
        }
        returnMoneyQO.setCompanyId(userAccount.getCompanyId());
        List<ReturnMoneyVO> returnMoneyVOList= returnMoneyDbservice.selectStatReturnMoney(returnMoneyQO,dateUnit);
        PageInfo<ReturnMoneyVO> pageInfo = new PageInfo<ReturnMoneyVO>(returnMoneyVOList);
        return new DhPageInfo<ReturnMoneyVO>(pageInfo, returnMoneyVOList);
    }


    @Override
    public DhPageInfo<ReturnMoneyVO> selectSuperStatReturnMoneyPage(ReturnMoneyQO returnMoneyQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(returnMoneyQO.getDateType())) {
            if ("thisWeek".equals(returnMoneyQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(returnMoneyQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(returnMoneyQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
            if ("topDay".equals(returnMoneyQO.getDateType())) {
                //昨天
                dateUnit = 4;
            }
            if ("day".equals(returnMoneyQO.getDateType())) {
                //今天
                dateUnit = 5;
            }
        }
        List<ReturnMoneyVO> returnMoneyVOList= returnMoneyDbservice.selectSuperStatReturnMoney(returnMoneyQO,dateUnit);
        PageInfo<ReturnMoneyVO> pageInfo = new PageInfo<ReturnMoneyVO>(returnMoneyVOList);
        return new DhPageInfo<ReturnMoneyVO>(pageInfo, returnMoneyVOList);
    }

    /**
     * 总部财务统计回款列表 - 分页
     * @param returnMoneyQO
     * @param pageIndex
     * @param pageSize
     * @param sortName
     * @param sortOrder
     * @return
     */
    /*@Override
    public DhPageInfo<ReturnMoneyVO> selectSuperStatReturnMoneyPage(ReturnMoneyQO returnMoneyQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<SysCompany> companyList = sysCompanyDbService.selectSysCompanyListByCompanyId(returnMoneyQO.getCompanyId(),returnMoneyQO.getCompName());
        Integer dateUnit = 0;
        List<ReturnMoneyVO> returnMoneyVOList = new ArrayList<>();
        for (int i=0;i<companyList.size();i++){
            boolean b = true;
            ReturnMoneyVO returnMoneyVO = new ReturnMoneyVO();
            returnMoneyVO.setFilialeName(companyList.get(i).getCompanyName());
            List<ReturnMoneyRedisVO> redisList = returnMoneyRedisService.getRedisReturnMoney(companyList.get(i).getCompanyId(),new Date());
            if (Objects.nonNull(redisList)){
                if (StringUtils.isNotBlank(returnMoneyQO.getArriveTimeStart()) && StringUtils.isNotBlank(returnMoneyQO.getArriveTimeEnd())){
                    b=false;
                    Integer startDate = Integer.valueOf(returnMoneyQO.getArriveTimeStart().replaceAll("-",""));
                    Integer endDate = Integer.valueOf(returnMoneyQO.getArriveTimeEnd().replaceAll("-",""));
                    for (int k=0;k<redisList.size();k++){
                        if (startDate <= redisList.get(k).getDate() && endDate >= redisList.get(k).getDate()){
                            if (Objects.isNull(returnMoneyVO.getScoreMoney())){
                                returnMoneyVO.setScoreMoney(new BigDecimal("0"));
                            }
                            if (Objects.isNull(returnMoneyVO.getArriveMoney())){
                                returnMoneyVO.setArriveMoney(new BigDecimal("0"));
                            }
                            if (Objects.isNull(redisList.get(k).getGradeMoney())){
                                redisList.get(k).setGradeMoney(new BigDecimal("0"));
                            }
                            if (Objects.isNull(redisList.get(k).getReturnMoney())){
                                redisList.get(k).setReturnMoney(new BigDecimal("0"));
                            }
                            returnMoneyVO.setScoreMoney(returnMoneyVO.getScoreMoney().add(redisList.get(k).getGradeMoney()));
                            returnMoneyVO.setArriveMoney(returnMoneyVO.getArriveMoney().add(redisList.get(k).getReturnMoney()));
                        }
                    }
                }
                if (StringUtils.isNotBlank(returnMoneyQO.getArriveTimeStart()) && b){
                    b=false;
                    Integer startDate = Integer.valueOf(returnMoneyQO.getArriveTimeStart().substring(0,10).replaceAll("-",""));
                    for (int k=0;k<redisList.size();k++){
                        if (startDate <= redisList.get(k).getDate()){
                            if (Objects.isNull(returnMoneyVO.getScoreMoney())){
                                returnMoneyVO.setScoreMoney(new BigDecimal("0"));
                            }
                            if (Objects.isNull(returnMoneyVO.getArriveMoney())){
                                returnMoneyVO.setArriveMoney(new BigDecimal("0"));
                            }
                            if (Objects.isNull(redisList.get(k).getGradeMoney())){
                                redisList.get(k).setGradeMoney(new BigDecimal("0"));
                            }
                            if (Objects.isNull(redisList.get(k).getReturnMoney())){
                                redisList.get(k).setReturnMoney(new BigDecimal("0"));
                            }
                            returnMoneyVO.setScoreMoney(returnMoneyVO.getScoreMoney().add(redisList.get(k).getGradeMoney()));
                            returnMoneyVO.setArriveMoney(returnMoneyVO.getArriveMoney().add(redisList.get(k).getReturnMoney()));
                        }
                    }
                }
                if (StringUtils.isNotBlank(returnMoneyQO.getArriveTimeEnd()) && b){
                    b=false;
                    Integer endDate = Integer.valueOf(returnMoneyQO.getArriveTimeEnd().substring(0,10).replaceAll("-",""));
                    for (int k=0;k<redisList.size();k++){
                        if (endDate >= redisList.get(k).getDate()){
                            if (Objects.isNull(returnMoneyVO.getScoreMoney())){
                                returnMoneyVO.setScoreMoney(new BigDecimal("0"));
                            }
                            if (Objects.isNull(returnMoneyVO.getArriveMoney())){
                                returnMoneyVO.setArriveMoney(new BigDecimal("0"));
                            }
                            if (Objects.isNull(redisList.get(k).getGradeMoney())){
                                redisList.get(k).setGradeMoney(new BigDecimal("0"));
                            }
                            if (Objects.isNull(redisList.get(k).getReturnMoney())){
                                redisList.get(k).setReturnMoney(new BigDecimal("0"));
                            }
                            returnMoneyVO.setScoreMoney(returnMoneyVO.getScoreMoney().add(redisList.get(k).getGradeMoney()));
                            returnMoneyVO.setArriveMoney(returnMoneyVO.getArriveMoney().add(redisList.get(k).getReturnMoney()));
                        }
                    }
                }
                if (!StringUtils.isBlank(returnMoneyQO.getDateType()) && Objects.nonNull(redisList) && b) {
                    if ("thisWeek".equals(returnMoneyQO.getDateType())) {
                        b = false;
                        //本周
                        dateUnit = 1;
                        Integer startDate = Integer.valueOf(DateUtils.getWeekStart().substring(0,10).replaceAll("-",""));
                        Integer endDate = Integer.valueOf(DateUtils.getWeekEnd().substring(0,10).replaceAll("-",""));
                        for (int k=0;k<redisList.size();k++){
                            if (startDate <= redisList.get(k).getDate() && endDate >= redisList.get(k).getDate()){
                                if (Objects.isNull(returnMoneyVO.getScoreMoney())){
                                    returnMoneyVO.setScoreMoney(new BigDecimal("0"));
                                }
                                if (Objects.isNull(returnMoneyVO.getArriveMoney())){
                                    returnMoneyVO.setArriveMoney(new BigDecimal("0"));
                                }
                                if (Objects.isNull(redisList.get(k).getGradeMoney())){
                                    redisList.get(k).setGradeMoney(new BigDecimal("0"));
                                }
                                if (Objects.isNull(redisList.get(k).getReturnMoney())){
                                    redisList.get(k).setReturnMoney(new BigDecimal("0"));
                                }
                                returnMoneyVO.setScoreMoney(returnMoneyVO.getScoreMoney().add(redisList.get(k).getGradeMoney()));
                                returnMoneyVO.setArriveMoney(returnMoneyVO.getArriveMoney().add(redisList.get(k).getReturnMoney()));
                            }
                        }
                    }
                    if ("thisMonth".equals(returnMoneyQO.getDateType())) {
                        b = false;
                        //本月
                        dateUnit = 2;
                        Integer startDate = Integer.valueOf(DateUtils.getMonthStart().substring(0,10).replaceAll("-",""));
                        Integer endDate = Integer.valueOf(DateUtils.getMonthEnd().substring(0,10).replaceAll("-",""));
                        for (int k=0;k<redisList.size();k++){
                            if (startDate <= redisList.get(k).getDate() && endDate >= redisList.get(k).getDate()){
                                if (Objects.isNull(returnMoneyVO.getScoreMoney())){
                                    returnMoneyVO.setScoreMoney(new BigDecimal("0"));
                                }
                                if (Objects.isNull(returnMoneyVO.getArriveMoney())){
                                    returnMoneyVO.setArriveMoney(new BigDecimal("0"));
                                }
                                if (Objects.isNull(redisList.get(k).getGradeMoney())){
                                    redisList.get(k).setGradeMoney(new BigDecimal("0"));
                                }
                                if (Objects.isNull(redisList.get(k).getReturnMoney())){
                                    redisList.get(k).setReturnMoney(new BigDecimal("0"));
                                }
                                returnMoneyVO.setScoreMoney(returnMoneyVO.getScoreMoney().add(redisList.get(k).getGradeMoney()));
                                returnMoneyVO.setArriveMoney(returnMoneyVO.getArriveMoney().add(redisList.get(k).getReturnMoney()));
                            }
                        }
                    }
                    if ("thisYear".equals(returnMoneyQO.getDateType())) {
                        b = false;
                        //本年
                        dateUnit = 3;
                        Integer startDate = Integer.valueOf(DateUtils.getYearStart().substring(0,10).replaceAll("-",""));
                        Integer endDate = Integer.valueOf(DateUtils.getYearEnd().substring(0,10).replaceAll("-",""));
                        for (int k=0;k<redisList.size();k++){
                            if (startDate <= redisList.get(k).getDate() && endDate >= redisList.get(k).getDate()){
                                if (Objects.isNull(returnMoneyVO.getScoreMoney())){
                                    returnMoneyVO.setScoreMoney(new BigDecimal("0"));
                                }
                                if (Objects.isNull(returnMoneyVO.getArriveMoney())){
                                    returnMoneyVO.setArriveMoney(new BigDecimal("0"));
                                }
                                if (Objects.isNull(redisList.get(k).getGradeMoney())){
                                    redisList.get(k).setGradeMoney(new BigDecimal("0"));
                                }
                                if (Objects.isNull(redisList.get(k).getReturnMoney())){
                                    redisList.get(k).setReturnMoney(new BigDecimal("0"));
                                }
                                returnMoneyVO.setScoreMoney(returnMoneyVO.getScoreMoney().add(redisList.get(k).getGradeMoney()));
                                returnMoneyVO.setArriveMoney(returnMoneyVO.getArriveMoney().add(redisList.get(k).getReturnMoney()));
                            }
                        }
                    }
                    if ("topDay".equals(returnMoneyQO.getDateType())) {
                        b = false;
                        //昨天
                        dateUnit = 4;
                        Integer startDate = Integer.valueOf(DateUtils.getYestoday().substring(0,10).replaceAll("-",""));
                        for (int k=0;k<redisList.size();k++){
                            if (startDate.toString().equals(redisList.get(k).getDate().toString())){
                                if (Objects.isNull(returnMoneyVO.getScoreMoney())){
                                    returnMoneyVO.setScoreMoney(new BigDecimal("0"));
                                }
                                if (Objects.isNull(returnMoneyVO.getArriveMoney())){
                                    returnMoneyVO.setArriveMoney(new BigDecimal("0"));
                                }
                                if (Objects.isNull(redisList.get(k).getGradeMoney())){
                                    redisList.get(k).setGradeMoney(new BigDecimal("0"));
                                }
                                if (Objects.isNull(redisList.get(k).getReturnMoney())){
                                    redisList.get(k).setReturnMoney(new BigDecimal("0"));
                                }
                                returnMoneyVO.setScoreMoney(returnMoneyVO.getScoreMoney().add(redisList.get(k).getGradeMoney()));
                                returnMoneyVO.setArriveMoney(returnMoneyVO.getArriveMoney().add(redisList.get(k).getReturnMoney()));
                            }
                        }
                    }
                    if ("day".equals(returnMoneyQO.getDateType())) {
                        b = false;
                        //今天
                        dateUnit = 5;
                        Integer startDate = Integer.valueOf(DateUtils.getToday().substring(0,10).replaceAll("-",""));
                        for (int k=0;k<redisList.size();k++){
                            if (startDate.toString().equals(redisList.get(k).getDate().toString())){
                                if (Objects.isNull(returnMoneyVO.getScoreMoney())){
                                    returnMoneyVO.setScoreMoney(new BigDecimal("0"));
                                }
                                if (Objects.isNull(returnMoneyVO.getArriveMoney())){
                                    returnMoneyVO.setArriveMoney(new BigDecimal("0"));
                                }
                                if (Objects.isNull(redisList.get(k).getGradeMoney())){
                                    redisList.get(k).setGradeMoney(new BigDecimal("0"));
                                }
                                if (Objects.isNull(redisList.get(k).getReturnMoney())){
                                    redisList.get(k).setReturnMoney(new BigDecimal("0"));
                                }
                                returnMoneyVO.setScoreMoney(returnMoneyVO.getScoreMoney().add(redisList.get(k).getGradeMoney()));
                                returnMoneyVO.setArriveMoney(returnMoneyVO.getArriveMoney().add(redisList.get(k).getReturnMoney()));
                            }
                        }
                    }
                }
                if (b && Objects.nonNull(redisList)){
                    for (int k=0;k<redisList.size();k++){
                        if (Objects.isNull(returnMoneyVO.getScoreMoney())){
                            returnMoneyVO.setScoreMoney(new BigDecimal("0"));
                        }
                        if (Objects.isNull(returnMoneyVO.getArriveMoney())){
                            returnMoneyVO.setArriveMoney(new BigDecimal("0"));
                        }
                        if (Objects.isNull(redisList.get(k).getGradeMoney())){
                            redisList.get(k).setGradeMoney(new BigDecimal("0"));
                        }
                        if (Objects.isNull(redisList.get(k).getReturnMoney())){
                            redisList.get(k).setReturnMoney(new BigDecimal("0"));
                        }
                        returnMoneyVO.setScoreMoney(returnMoneyVO.getScoreMoney().add(redisList.get(k).getGradeMoney()));
                        returnMoneyVO.setArriveMoney(returnMoneyVO.getArriveMoney().add(redisList.get(k).getReturnMoney()));
                    }
                }
            }
            if (Objects.isNull(returnMoneyVO.getScoreMoney())){
                returnMoneyVO.setScoreMoney(new BigDecimal("0"));
            }
            if (Objects.isNull(returnMoneyVO.getArriveMoney())){
                returnMoneyVO.setArriveMoney(new BigDecimal("0"));
            }
            returnMoneyVOList.add(returnMoneyVO);
            if ((new BigDecimal("0").equals(returnMoneyVO.getArriveMoney()) || new BigDecimal("0.00").equals(returnMoneyVO.getArriveMoney()) || Objects.isNull(returnMoneyVO.getArriveMoney()))
                    && (new BigDecimal("0").equals(returnMoneyVO.getScoreMoney() ) || new BigDecimal("0.00").equals(returnMoneyVO.getScoreMoney())|| Objects.isNull(returnMoneyVO.getArriveMoney()))){
            }else {
                //returnMoneyVOList.add(returnMoneyVO);
            }
        }
        //List<ReturnMoneyVO> returnMoneyVOList= returnMoneyDbservice.selectSuperStatReturnMoney(returnMoneyQO,dateUnit);
        PageInfo<SysCompany> pageInfo = new PageInfo<SysCompany>(companyList);
        return new DhPageInfo<ReturnMoneyVO>(pageInfo, returnMoneyVOList);
    }*/

    /**
     * 总部财务统计回款列表 list
     * @return
     */
    @Override
    public List<ReturnMoneyVO> selectSuperStatReturnMoney(ReturnMoneyQO returnMoneyQO) {
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(returnMoneyQO.getDateType())) {
            if ("thisWeek".equals(returnMoneyQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(returnMoneyQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(returnMoneyQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
            if ("topDay".equals(returnMoneyQO.getDateType())) {
                //昨天
                dateUnit = 4;
            }
            if ("day".equals(returnMoneyQO.getDateType())) {
                //今天
                dateUnit = 5;
            }
        }
        List<ReturnMoneyVO> list= returnMoneyDbservice.selectSuperStatReturnMoney(returnMoneyQO,dateUnit);
        return list;
    }

    /**
     * 分公司财务统计回款列表
     * @param returnMoneyQO
     * @param pageIndex
     * @param pageSize
     * @param sortName
     * @param sortOrder
     * @return
     */
    @Override
    public DhPageInfo<ReturnMoneyVO> selectStatBackMoneyPage(ReturnMoneyQO returnMoneyQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(returnMoneyQO.getDateType())) {
            if ("thisWeek".equals(returnMoneyQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(returnMoneyQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(returnMoneyQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
            if ("topDay".equals(returnMoneyQO.getDateType())) {
                //昨天
                dateUnit = 4;
            }
            if ("day".equals(returnMoneyQO.getDateType())) {
                //今天
                dateUnit = 5;
            }
        }
        returnMoneyQO.setCompanyId(userAccount.getCompanyId());
        List<ReturnMoneyVO> returnMoneyVOList= returnMoneyDbservice.selectStatBackMoney(returnMoneyQO,dateUnit);
        PageInfo<ReturnMoneyVO> pageInfo = new PageInfo<ReturnMoneyVO>(returnMoneyVOList);
        return new DhPageInfo<ReturnMoneyVO>(pageInfo, returnMoneyVOList);
    }

    /**
     * 总部财务统计退款列表
     * @param returnMoneyQO
     * @param pageIndex
     * @param pageSize
     * @param sortName
     * @param sortOrder
     * @return
     */
    @Override
    public DhPageInfo<ReturnMoneyVO> selectSuperStatBackMoney(ReturnMoneyQO returnMoneyQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(returnMoneyQO.getDateType())) {
            if ("thisWeek".equals(returnMoneyQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(returnMoneyQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(returnMoneyQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
            if ("topDay".equals(returnMoneyQO.getDateType())) {
                //昨天
                dateUnit = 4;
            }
            if ("day".equals(returnMoneyQO.getDateType())) {
                //今天
                dateUnit = 5;
            }
        }
        List<ReturnMoneyVO> returnMoneyVOList= returnMoneyDbservice.selectSuperStatBackMoney(returnMoneyQO,dateUnit);
        PageInfo<ReturnMoneyVO> pageInfo = new PageInfo<ReturnMoneyVO>(returnMoneyVOList);
        return new DhPageInfo<ReturnMoneyVO>(pageInfo, returnMoneyVOList);
    }

    /**
     * 总部财务统计退款列表
     * @param returnMoneyQO
     * @return
     */
    @Override
    public List<ReturnMoneyVO> selectStatBackMoney(ReturnMoneyQO returnMoneyQO) {
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(returnMoneyQO.getDateType())) {
            if ("thisWeek".equals(returnMoneyQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(returnMoneyQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(returnMoneyQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
            if ("topDay".equals(returnMoneyQO.getDateType())) {
                //昨天
                dateUnit = 4;
            }
            if ("day".equals(returnMoneyQO.getDateType())) {
                //今天
                dateUnit = 5;
            }
        }
        List<ReturnMoneyVO> returnMoneyVOList= returnMoneyDbservice.selectSuperStatBackMoney(returnMoneyQO,dateUnit);
        return returnMoneyVOList;
    }

    /**
     * 导入退款记录
     * @param list
     * @param companyId
     * @return
     */
    @SneakyThrows
    @Override
    public JSONObject importBackMoney(List<ImportBckMoneyVO> list, String companyId) {
        //返回的结果集
        JSONObject jsonObject = new JSONObject();
        //导入数量
        int importNum = 0;
        //重复的行数
        String repeatIdStr = "";
        //失败行数
        String importFailIdStr = "";
        for (int i = 0; i < list.size(); i++) {
            boolean b =true;
            ImportBckMoneyVO importVO = list.get(i);
            List<ImportFailureLogVO> logVOList = importFailureLogDbService.selectImportFailureLogByNameAndType(importVO.getBackCode(),10,companyId,null);
            if (logVOList.size() > 0){
                for (int k=0;k<logVOList.size();k++){
                    if (logVOList.get(k).getImportData().equals(JSONObject.toJSONString(importVO))){
                        if (logVOList.get(k).getLogType().equals("1")){
                            //重复
                            if (StringUtils.isBlank(repeatIdStr)) {
                                repeatIdStr = String.valueOf(i + 1);
                            } else {
                                repeatIdStr = repeatIdStr + "," + (i + 1);
                            }
                        }else if (logVOList.get(k).getLogType().equals("2")){
                            //导入失败
                            if (StringUtils.isBlank(importFailIdStr)) {
                                importFailIdStr = String.valueOf(i + 1);
                            } else {
                                importFailIdStr = importFailIdStr + "," + (i + 1);
                            }
                        }
                        b =false;
                        break;
                    }
                }
            }
            if (b){
                String reasonForFailure = "数据错误";
                CustomerProductOrderVO order = productOrderDbService.selectOrderByNumber(importVO.getOrderCode());
                if (Objects.isNull(order)){
                    reasonForFailure = "第"+(i+2)+"行,订单编号："+importVO.getBackCode()+"订单匹配失败";
                    insertImportFailureLog(importVO, 2, companyId, reasonForFailure);
                    //导入失败
                    if (StringUtils.isBlank(importFailIdStr)) {
                        importFailIdStr = String.valueOf(i + 1);
                    } else {
                        importFailIdStr = importFailIdStr + "," + (i + 1);
                    }
                    b=false;
                }
                if (b){
                    List<ReturnMoneyVO> returnMoneyListVO = returnMoneyDbservice.selectReturnMoneyByOrderIdAndMoney(order.getProductOrderId());
                    for (int k=0;k<returnMoneyListVO.size();k++){
                        if (returnMoneyListVO.get(i).getArriveMoney().toString().equals(importVO.getBackMoney())){
                            b=false;
                        }
                    }
                    if (b) {
                        ReturnMoneyVO returnMoneyVO = returnMoneyDbservice.selectImportReturnMoneyByOrderId(order.getProductOrderId());
                        if (Objects.isNull(returnMoneyVO)){
                            reasonForFailure = "第"+(i+2)+"行,订单编号："+importVO.getBackCode()+"匹配回款记录失败";
                            insertImportFailureLog(importVO, 2, companyId, reasonForFailure);
                            //导入失败
                            if (StringUtils.isBlank(importFailIdStr)) {
                                importFailIdStr = String.valueOf(i + 1);
                            } else {
                                importFailIdStr = importFailIdStr + "," + (i + 1);
                            }
                            b=false;
                        }
                        if (b){
                            Date backDate = null;
                            if (Objects.nonNull(importVO.getBackDate())) {
                                //同一个Excel有不一样的时间格式……
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                backDate = simpleDateFormat.parse(importVO.getBackDate());
                            }
                            ReturnMoney returnMoney = new ReturnMoney();
                            returnMoney.setReturnMoneyId(returnMoneyVO.getReturnMoneyId());
                            returnMoney.setIsBack(1);
                            returnMoney.setBackDate(backDate);
                            returnMoneyDbservice.updateReturnMoney(returnMoney);
                            importNum = importNum + 1;
                        }
                    } else {
                        //insertImportFailureLog(importVO, 1, companyId, "第"+i + 1+"行，"+importVO.getUserAccount()+"账号已存在");
                        //重复
                        if (StringUtils.isBlank(repeatIdStr)) {
                            repeatIdStr = String.valueOf(i + 1);
                        } else {
                            repeatIdStr = repeatIdStr + "," + (i + 1);
                        }
                    }
                }

            }

        }
        jsonObject.put("importCallNum", importNum);
        jsonObject.put("repeatIdStr", repeatIdStr);
        jsonObject.put("importFailIdStr", importFailIdStr);
        return jsonObject;
    }

    @Override
    public JSONObject importUpdateReturnMoney(List<ImportReturnMoneyVO> list, String companyId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        for (int i=0;i< list.size();i++){
            if (!"分公司".equals(list.get(i).getArriveUnitName())){
                ReturnMoney returnMoney = new ReturnMoney();
                ReturnMoneyVO returnMoneyVO= returnMoneyDbservice.selectReturnMoneyByNumber(list.get(i).getArriveNum());
                if (Objects.nonNull(returnMoneyVO)){
                    returnMoney.setReturnMoneyId(returnMoneyVO.getReturnMoneyId());
                    returnMoney.setArriveUnitName(list.get(i).getArriveUnitName());
                    if ("北京财税研究院".equals(list.get(i).getArriveUnitName())){
                        returnMoney.setArriveAccountType(1);
                    }
                    if ("大成方略网络科技有限公司".equals(list.get(i).getArriveUnitName())){
                        returnMoney.setArriveAccountType(2);
                    }
                    if ("北京大成方略财务顾问有限公司".equals(list.get(i).getArriveUnitName())){
                        returnMoney.setArriveAccountType(3);
                    }
                    if ("北京大成方略纳税人俱乐部有限公司".equals(list.get(i).getArriveUnitName())){
                        returnMoney.setArriveAccountType(4);
                    }
                    if ("大成方略纳税人俱乐部股份有限公司".equals(list.get(i).getArriveUnitName())){
                        returnMoney.setArriveAccountType(5);
                    }
                    returnMoney.setUpdateBy(userAccount.getAccountId());
                    returnMoney.setUpdateTm(new Date());
                    returnMoney.setDataSource(1);
                    returnMoneyDbservice.updateReturnMoney(returnMoney);
                }
            }
        }
        return null;
    }

    /**
     * 记录导入失败日志
     *
     * @param importVO
     * @param type
     */
    public void insertImportFailureLog(ImportBckMoneyVO importVO, Integer type, String companyId, String reasonForFailure) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        ImportFailureLog importFailureLog = new ImportFailureLog();
        importFailureLog.setImportFailureLogId(CommonUtils.getGUID());
        importFailureLog.setOperatePeopleId(userAccount.getAccountId());
        importFailureLog.setOperateTime(new Date());
        importFailureLog.setOperateType("10");
        importFailureLog.setImportName(importVO.getBackCode());
        importFailureLog.setReasonForFailure(reasonForFailure);
        importFailureLog.setImportData(JSONObject.toJSONString(importVO));
        importFailureLog.setLogType(String.valueOf(type));
        importFailureLog.setCompanyId(companyId);
        importFailureLogDbService.insertImportFailureLog(importFailureLog);
    }

    /**
     * 录入回款
     * @param returnMoney
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Map<String,Object> addReturnMoney(ReturnMoney returnMoney,Integer dataSourceType,boolean preReturnMoneyFlag) {
        if (preReturnMoneyFlag){
            returnMoney.setDelFlag(2);  //预回款标识
        }
        //没有小数点的加上小数点，省的比较金额有问题
        if (returnMoney.getArriveMoney().toString().indexOf(".") == -1){
            BigDecimal newMoney=new BigDecimal(returnMoney.getArriveMoney().toString()+".00");
            returnMoney.setArriveMoney(newMoney);
        }
        //获取订单信息
        CustomerProductOrderVO order=productOrderDbService.getOrderInfoById(returnMoney.getOrderId());
        Customer customer = customerDbService.selectCustomerById(order.getCustomerId());
        //合同信息
        CustomerContract contract=contractDbService.selectContractById(order.getContractId());
        Map<String,Object> map = new HashMap<>();
        if (Objects.nonNull(order)){
            if (Objects.nonNull(order.getOrderType())){
                returnMoney.setVipType(Integer.valueOf(order.getOrderType()));
            }
            returnMoney.setCustomerId(order.getCustomerId());
            returnMoney.setContractId(order.getContractId());
            returnMoney.setSalesmanId(order.getCreatePeopleId());
            returnMoney.setFilialeId(order.getAffiliationCompanyId());
            returnMoney.setOrderNumber(order.getOrderNumber());
        }
        returnMoney.setReturnMoneyId(CommonUtils.getGUID());
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        returnMoney.setCreateBy(userAccount.getAccountId());
        returnMoney.setCreateTm(new Date());
        returnMoney.setArriveNum("RM"+new Date().getTime());
        returnMoney.setDataSource(dataSourceType);
        returnMoney.setCustomerId(customer.getCustomerId());
        returnMoney.setCustomerName(customer.getCustomerName());
        returnMoney.setContractType(contract.getContractType());
        returnMoney.setContractNumber(contract.getContractNumber());
        List<String> returnMoneyIdList = new ArrayList<>();
        //全额回款
        if(0 == returnMoney.getArriveType()){
            if (Objects.isNull(order.getPaidBackAmount())){
                order.setPaidBackAmount(new BigDecimal("0"));
            }
            if (returnMoney.getArriveMoney().compareTo(contract.getContractReceivables().subtract(order.getPaidBackAmount())) != 0){
                map.put("code",ResponseCodeEnum.ALL_RETURN_MONEY_MAX.getResponseCode());
                return map;
            }
            Date arriveTime = null;
            for (int i=1;i<4;i++){
                if (i == 3){
                    //补款升级的产品
                    i = 5;
                }
                FinishOrderProduct finishOrderProduct = null;
                //查询finish表所有产品（不含赠品）
                List<FinishOrderProduct> finishList = finishOrderDBservice.selectFinishOrderProductList(String.valueOf(i),null,returnMoney.getOrderId());
                for (int k=0;k<finishList.size();k++){
                    BigDecimal big = returnMoneyDbservice.selectOrderProductReturnMoneyCount(finishList.get(k).getFinishOrderProductId(),returnMoney.getOrderId());
                    if (Objects.isNull(big)){
                        big = new BigDecimal("0");
                    }
                    returnMoney.setArriveNum("RM"+new Date().getTime()+k);
                    returnMoney.setArriveMoney(finishList.get(k).getProductFinalPrice().subtract(big));
                    returnMoney.setFinishOrderProductNum(finishList.get(k).getFinishOrderProductNum());
                    returnMoney.setProductId(finishList.get(k).getProductId());
                    returnMoney.setProductNumber(finishList.get(k).getProductCode());
                    returnMoney.setProductName(finishList.get(k).getProductName());
                    returnMoney.setProductCategories(finishList.get(k).getProductCategories());
                    returnMoney.setOrderDetailType(finishList.get(k).getOrderDetailType());
                    returnMoney.setContractType(finishList.get(k).getContractType());
                    returnMoney.setFinishOrderProductId(finishList.get(k).getFinishOrderProductId());
                    returnMoney.setFinishOrderProductNum(finishList.get(k).getFinishOrderProductNum());
                    Map<String, Object> scoreMoneyMap = countReturnMoneyScoreMoney(returnMoney, finishList.get(k), contract, k);
                    returnMoney = (ReturnMoney) scoreMoneyMap.get("returnMoney");
                    List<String> qbhkReturnMoneyIds = (List<String>) scoreMoneyMap.get("returnMoneyIds");
                    returnMoneyIdList.addAll(qbhkReturnMoneyIds);
                    //业绩计算比例
                    //BigDecimal ratio = customerMemberProductDbService.selectProductPerformanceRatio(finishList.get(k).getProductCategories(),finishList.get(k).getProductId());
                    finishOrderProduct = finishList.get(k);
                    finishOrderProduct.setProductStatus("3");
                    //计算业绩金额
                    if(Objects.isNull(finishOrderProduct.getPerformanceConversionRatio())){
                        finishOrderProduct.setGradeMoney(new BigDecimal("0"));
                    }else if (Objects.nonNull(finishOrderProduct.getGradeMoney())){
                        finishOrderProduct.setGradeMoney(finishOrderProduct.getGradeMoney().add(returnMoney.getArriveMoney().multiply(finishOrderProduct.getPerformanceConversionRatio())));
                    }else {
                        finishOrderProduct.setGradeMoney(returnMoney.getArriveMoney().multiply(finishOrderProduct.getPerformanceConversionRatio()));
                    }
                    if (Objects.isNull(arriveTime)){
                        arriveTime = returnMoney.getArriveTime();
                    }else if (arriveTime.getTime() < returnMoney.getArriveTime().getTime()){
                        arriveTime = returnMoney.getArriveTime();
                    }
                    finishOrderProduct.setArriveTime(arriveTime);
                    finishOrderProduct.setUpdatePeopleId(userAccount.getAccountId());
                    finishOrderProduct.setUpdateTm(new Date());
                    finishOrderDBservice.updateFinishOrderProduct(finishOrderProduct);
                }
                if ("1".equals(order.getContractOtherType()) && Objects.nonNull(finishOrderProduct)){ //补款升级产品
                    //升级之前的finish
                    FinishOrderProduct f = finishOrderDBservice.selectFinishOrderProductById(contract.getUpgradeRelateFinishProductId());
                    //两个产品业绩比例一样就不需要补第二条TRM的
                    if(finishOrderProduct.getPerformanceConversionRatio().compareTo(f.getPerformanceConversionRatio()) != 0){
                        returnMoney.setScoreConvertRatio(finishOrderProduct.getPerformanceConversionRatio().subtract(f.getPerformanceConversionRatio()));
                        if (new BigDecimal("0").compareTo(f.getProductFinalPrice()) == -1){
                            returnMoney.setScoreMoney(f.getProductFinalPrice().multiply(returnMoney.getScoreConvertRatio()));
                        }
                        finishOrderProduct.setPerformanceConversionRatio(returnMoney.getScoreConvertRatio());
                        returnMoney.setArriveMoney(null);
                        returnMoney.setArriveNum("TRM"+new Date().getTime());
                        returnMoney.setCreateTm(new Date());
                        returnMoney.setCreateBy(userAccount.getAccountId());
                        Map<String, Object> bksjMap = countReturnMoneyScoreMoney(returnMoney, finishOrderProduct, contract, null);
                        List<String> bksjList = (List<String>) bksjMap.get("returnMoneyIds");
                        returnMoneyIdList.addAll(bksjList);
                        //作废原订单产品号
                        customerProductOrderService.backProduct(f.getProductOrderId(),f.getFinishOrderProductNum());
                    }
                }
            }
            //附加费用
            if (Objects.nonNull(order.getOrderSurcharge()) && new BigDecimal("0").compareTo(order.getOrderSurcharge()) == -1){
                returnMoney.setReturnMoneyId(CommonUtils.getGUID());
                returnMoney.setArriveNum("RM"+new Date().getTime());
                returnMoney.setArriveMoney(order.getOrderSurcharge());
                returnMoney.setFinishOrderProductId(null);
                returnMoney.setFinishOrderProductNum("0001");
                returnMoney.setProductName("附加费用");
                returnMoney.setProductId(null);
                returnMoney.setProductNumber(null);
                returnMoney.setProductCategories("0");
                returnMoney.setScoreConvertRatio(new BigDecimal("0"));
                returnMoney.setScoreMoney(new BigDecimal("0"));
                returnMoney.setOrderDetailType(null);
                List<String> fjfyList = insertOrderSurcharge(returnMoney, contract);
                returnMoneyIdList.addAll(fjfyList);
            }
            order.setPaidBackAmount(null);
            returnMoney.setArriveMoney(contract.getContractReceivables());

            //如果是补款升级合同需要把原来订单产品的会员卡进行作废
            if("1".equals(contract.getContractOtherType())){
                String upgradeRelateFinishProductId = contract.getUpgradeRelateFinishProductId();
                FinishOrderProduct finishOrderProduct = finishOrderDBservice.selectFinishOrderProductById(upgradeRelateFinishProductId);
                customerProductOrderService.backProduct(finishOrderProduct.getProductOrderId(),finishOrderProduct.getFinishOrderProductNum());
            }
        }
        //按产品回款
        if (returnMoney.getArriveType() == 1){
            //该产品不是附加费用
            if (!"0001".equals(returnMoney.getFinishOrderProductNum()) && !"附加费用".equals(returnMoney.getProductName())){
                FinishOrderProduct finish = null;
                if (StringUtils.isNotBlank(returnMoney.getFinishOrderProductId())){
                    finish = finishOrderDBservice.selectFinishOrderProductById(returnMoney.getFinishOrderProductId());
                }else {
                    //finishOrderDBservice.select
                }
                BigDecimal big = returnMoneyDbservice.selectOrderProductReturnMoneyCount(returnMoney.getFinishOrderProductId(),order.getProductOrderId());
                if (Objects.isNull(big)){
                    big = new BigDecimal("0");
                }
                FinishOrderProduct finishOrderProduct = finishOrderDBservice.selectFinishOrderProductById(returnMoney.getFinishOrderProductId());
                returnMoney.setProductNumber(finishOrderProduct.getProductCode());
                Map<String, Object> returnMoneyScoreMoneyMap = countReturnMoneyScoreMoney(returnMoney, finish, contract, 0);
                returnMoney = (ReturnMoney) returnMoneyScoreMoneyMap.get("returnMoney");
                List<String> cphkList = (List<String>) returnMoneyScoreMoneyMap.get("returnMoneyIds");
                returnMoneyIdList.addAll(cphkList);//产品回款的回款id
                Date arriveTime = returnMoney.getArriveTime();

                if (Objects.nonNull(finishOrderProduct.getProductFinalPrice())){
                    //判断回款金额，当前产品是否全部回款
                    if (returnMoney.getArriveMoney().compareTo(finishOrderProduct.getProductFinalPrice().subtract(big)) == 0){
                        finishOrderProduct.setProductStatus("3");
                    }else if (!new BigDecimal("0").equals(returnMoney.getArriveMoney())&& !new BigDecimal("0.00").equals(returnMoney.getArriveMoney())){
                        finishOrderProduct.setProductStatus("2");//产品金额不为0，并且回款完成
                    }

                    //计算业绩金额
                    if(Objects.isNull(finishOrderProduct.getPerformanceConversionRatio())){
                        finishOrderProduct.setGradeMoney(new BigDecimal("0"));
                    }else if (Objects.nonNull(finishOrderProduct.getGradeMoney())){
                        finishOrderProduct.setGradeMoney(finishOrderProduct.getGradeMoney().add(returnMoney.getArriveMoney().multiply(finishOrderProduct.getPerformanceConversionRatio())));
                    }else {
                        finishOrderProduct.setGradeMoney(returnMoney.getArriveMoney().multiply(finishOrderProduct.getPerformanceConversionRatio()));
                    }
                }
                if (Objects.isNull(arriveTime)){
                    arriveTime = returnMoney.getArriveTime();
                }else if (arriveTime.getTime() < returnMoney.getArriveTime().getTime()){
                    arriveTime = returnMoney.getArriveTime();
                }
                finishOrderProduct.setArriveTime(arriveTime);
                finishOrderProduct.setUpdatePeopleId(userAccount.getAccountId());
                finishOrderProduct.setUpdateTm(new Date());
                //修改finish表回款状态
                finishOrderDBservice.updateFinishOrderProduct(finishOrderProduct);
            }else { //该产品是附加费用
                if (Objects.nonNull(order.getOrderSurcharge()) && new BigDecimal("0").compareTo(order.getOrderSurcharge()) == -1){
                    returnMoney.setFinishOrderProductId(null);
                    returnMoney.setFinishOrderProductNum("0001");
                    returnMoney.setProductName("附加费用");
                    returnMoney.setProductId(null);
                    returnMoney.setProductNumber(null);
                    returnMoney.setProductCategories("0");
                    returnMoney.setScoreConvertRatio(new BigDecimal("0"));
                    returnMoney.setScoreMoney(new BigDecimal("0"));
                    returnMoney.setOrderDetailType(null);
                    List<String> cpfjfyList = insertOrderSurcharge(returnMoney, contract);
                    returnMoneyIdList.addAll(cpfjfyList);
                }
            }

        }
        //填充订单表数据
        if (Objects.nonNull(order.getPaidBackAmount())){
            order.setPaidBackAmount(order.getPaidBackAmount().add(returnMoney.getArriveMoney()));
        }else {
            order.setPaidBackAmount(returnMoney.getArriveMoney());
        }
        //判断合同回款金额是否全部回款
        if (preReturnMoneyFlag){   //是否预回款
            order.setOrderStatus("5");
        }else if (order.getPaidBackAmount().toString().equals(contract.getContractReceivables().toString())){  //全部回款
            order.setOrderStatus("2");
            order.setOrderCompleteTm(new Date());
        }else {//部分回款
            order.setOrderStatus("4");
        }
        //更新订单表
        productOrderDbService.updateOrderComplete(order);
        //更新合同
        contract = updateCustomerContract(returnMoney,order,1);
        //查合同
        CustomerContractDetailVO contractInfo=contractDbService.selectCustomerContractVODetail(returnMoney.getContractId());
        //订单完成同步chs_finish_order_product;循环三次，分别查询普通产品、活动产品、赠品产品
        if ("2".equals(order.getOrderStatus())){
            AddFinishResultVO addFinishResultVO;
            //List<FinishOrderProduct> finishList=productOrderDbService.getFinishProductList(returnMoney.getOrderId());
            //if (finishList.size()>0){
                //addFinishResultVO = addFinishProductList(finishList,0,contractInfo.getContractType(),returnMoney,1);
                //returnMoneyToRedis(new BigDecimal("0"),returnMoney.getFilialeId(),returnMoney.getArriveMoney(),returnMoney.getArriveTime());
           // }
            //维护客户表会员到期时间、会员开始时间、客户状态、会员等级
            // 2、4为会员合同
            if ("2".equals(contract.getContractType()) || "4".equals(contract.getContractType())){
                updateCustomer(contract);
            }
            //发送消息 白剑版
            sendMessage(order);
            //全部完成插入一条消息 李向谦
            messagePromptDbService.insertMsg(contract,1);
        }else {
            returnMoneyToRedis(new BigDecimal("0"),returnMoney.getFilialeId(),returnMoney.getArriveMoney(),returnMoney.getArriveTime());
        }
//        return null;
        map.put("code",ResponseCodeEnum.OK.getResponseCode());
        map.put("returnMoneyIds",returnMoneyIdList);
        return map;//返回回款表id
    }

    public void sendMessage(CustomerProductOrderVO order){
        MessageAddQO message = new MessageAddQO();
        message.setAccountId(order.getCreatePeopleId());
        message.setCompanyId(order.getAffiliationCompanyId());
        message.setNewsType(3);
        message.setTheme("订单回款");
        message.setNewsDetail("您的有一笔订单回款已完成，订单号为：" +
                "<a class=\"js-create-tab\" data-title=\"订单详情\" data-url=\"/front/orderManager/orderDetail?productOrderId=" + order.getProductOrderId() +"&contractId="+order.getContractId()+ "\">\n" +
                "                        <span class=\"text\">"+ order.getOrderNumber()  +"</span>\n" +
                "</a>\n" +
                ",系统消息请勿回复");
        messageService.addMessage(message);
    }

    /**
     * 添加附加费用汇款记录
     * @param returnMoney
     * @param contract
     */
    private List<String> insertOrderSurcharge(ReturnMoney returnMoney, CustomerContract contract) {
        returnMoney.setScoreConvertRatio(new BigDecimal("0"));
        //定义回款id集合（流水关联用）
        List<String> returnMoneyIds = new ArrayList<>();
        //是合作开发
        if ("1".equals(contract.getWhetherCooperateDevelopment())){
            BigDecimal returnMoneyS = new BigDecimal("0");
            BigDecimal arriveMoney = returnMoney.getArriveMoney();
            List<CustomerContractDeveloper> developerList = customerContractDeveloperDbService.selectCustomerContractDeveloperList(contract.getContractId());
            for (int p=0;p < developerList.size();p++){
                returnMoney.setReturnMoneyId(CommonUtils.getGUID());
                returnMoney.setArriveNum("RM"+new Date().getTime()+p);
                UserAccount developerUser = userAccountDbService.selectUserAccountByUserId(developerList.get(p).getCoDeveloper());
                if (developerList.size() -1 > p){
                    returnMoney.setArriveMoney(arriveMoney.multiply(developerList.get(p).getAllocationRatio()).divide(new BigDecimal("1")).setScale(0,BigDecimal.ROUND_DOWN));
                    returnMoneyS = returnMoneyS.add(returnMoney.getArriveMoney());
                }else {//最后一个人分钱的时候直接用总价减去前几个人分的钱，避免金额除不尽，总金额对不上
                    returnMoney.setArriveMoney(arriveMoney.subtract(returnMoneyS));
                }
                returnMoney.setSalesmanId(developerUser.getAccountId());
                returnMoney.setFilialeId(developerUser.getCompanyId());
                //插入回款表
                returnMoneyDbservice.addReturnMoney(returnMoney);
                returnMoneyIds.add(returnMoney.getReturnMoneyId());
                returnMoneyRedisService.returnMoneyToRedis(returnMoney.getFilialeId(),returnMoney.getScoreMoney(),returnMoney.getArriveMoney(),returnMoney.getArriveTime());
            }
            returnMoney.setArriveMoney(arriveMoney);
        }else {
            returnMoneyDbservice.addReturnMoney(returnMoney);
            returnMoneyIds.add(returnMoney.getReturnMoneyId());
            returnMoneyRedisService.returnMoneyToRedis(returnMoney.getFilialeId(),returnMoney.getScoreMoney(),returnMoney.getArriveMoney(),returnMoney.getArriveTime());
        }
        return returnMoneyIds;
    }

    /**
     * 计算回款业绩
     * @param returnMoney
     * @param finish
     * @param contract
     * @param num 产品序号
     * @return
     */
    public Map<String,Object> countReturnMoneyScoreMoney(ReturnMoney returnMoney,FinishOrderProduct finish,CustomerContract contract,Integer num){
        returnMoney.setReturnMoneyId(CommonUtils.getGUID());
        BigDecimal ratio = finish.getPerformanceConversionRatio();
        returnMoney.setScoreConvertRatio(ratio);
        Map<String,Object> returnMoneyMap = new HashMap<>();//存储回款记录对象
        //如果业绩比例为0，业绩也金额也为0
        if (new BigDecimal("0.00").compareTo(ratio) == 0 || new BigDecimal("0").compareTo(ratio) == 0){
            returnMoney.setScoreMoney(new BigDecimal("0"));
        }
        List<String> returnMoneyIdList = new ArrayList<>();
        //是合作开发
        if ("1".equals(contract.getWhetherCooperateDevelopment())){
            boolean b = false;
            if (null == returnMoney.getArriveMoney()){
                FinishOrderProduct f = finishOrderDBservice.selectFinishOrderProductById(contract.getUpgradeRelateFinishProductId());
                returnMoney.setArriveMoney(f.getProductFinalPrice());
                b=true;
            }
            BigDecimal returnMoneyS = new BigDecimal("0");
            BigDecimal arriveMoney = returnMoney.getArriveMoney();
            List<CustomerContractDeveloper> developerList = customerContractDeveloperDbService.selectCustomerContractDeveloperList(contract.getContractId());
            for (int p=0;p < developerList.size();p++){
                returnMoney.setReturnMoneyId(CommonUtils.getGUID());
                returnMoney.setArriveNum("RM"+new Date().getTime()+num+p);
                UserAccount developerUser = userAccountDbService.selectUserAccountByUserId(developerList.get(p).getCoDeveloper());
                if (Objects.nonNull(ratio)){
                    if (developerList.size() -1 > p){
                        returnMoney.setScoreMoney(arriveMoney.multiply(ratio).multiply(developerList.get(p).getAllocationRatio()).divide(new BigDecimal("1")).setScale(0,BigDecimal.ROUND_DOWN));
                        returnMoney.setArriveMoney(arriveMoney.multiply(ratio).multiply(developerList.get(p).getAllocationRatio()).divide(new BigDecimal("1")).setScale(0,BigDecimal.ROUND_DOWN));
                        //returnMoneyDbservice.selectOrderProductReturnMoneyCount(finish.getFinishOrderProductId(),finish.getProductOrderId())
                        returnMoneyS = returnMoneyS.add(returnMoney.getArriveMoney());
                    }else {//最后一个人分钱的时候直接用总价减去前几个人分的钱，避免金额除不尽，总金额对不上
                        returnMoney.setArriveMoney(arriveMoney.subtract(returnMoneyS));
                        returnMoney.setScoreMoney(returnMoney.getArriveMoney().multiply(ratio));
                    }
                }
                returnMoney.setSalesmanId(developerUser.getAccountId());
                returnMoney.setFilialeId(developerUser.getCompanyId());
                if (b){
                    returnMoney.setArriveMoney(new BigDecimal("0"));
                }
                //插入回款表
                returnMoneyDbservice.addReturnMoney(returnMoney);
                returnMoneyIdList.add(returnMoney.getReturnMoneyId());
                returnMoneyRedisService.returnMoneyToRedis(returnMoney.getFilialeId(),returnMoney.getScoreMoney(),returnMoney.getArriveMoney(),returnMoney.getArriveTime());
            }
            returnMoney.setArriveMoney(arriveMoney);
        }else {
            if (Objects.nonNull(ratio) && Objects.nonNull(returnMoney.getArriveMoney())){
                returnMoney.setScoreMoney(returnMoney.getArriveMoney().multiply(ratio));
            }
            returnMoneyDbservice.addReturnMoney(returnMoney);
            returnMoneyIdList.add(returnMoney.getReturnMoneyId());
            returnMoneyRedisService.returnMoneyToRedis(returnMoney.getFilialeId(),returnMoney.getScoreMoney(),returnMoney.getArriveMoney(),returnMoney.getArriveTime());
        }
        returnMoneyMap.put("returnMoney",returnMoney);
        returnMoneyMap.put("returnMoneyIds",returnMoneyIdList);//回款id集合
        return returnMoneyMap;
    }

    /**
     * 修改回款信息
     * @param returnMoney
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public String updateReturnMoney(ReturnMoney returnMoney) {
        UserAccount user = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        returnMoney.setUpdateBy(user.getAccountId());
        returnMoney.setUpdateTm(new Date());
        ReturnMoneyVO returnMoneyVO = returnMoneyDbservice.selectReturnMoneyById(returnMoney.getReturnMoneyId());
        if (returnMoney.getArriveMoney().toString().indexOf(".") == -1){
            BigDecimal newMoney=new BigDecimal(returnMoney.getArriveMoney().toString()+".00");
            returnMoney.setArriveMoney(newMoney);
        }
        if (returnMoneyVO.getArriveType() == 0 && returnMoney.getArriveMoney().compareTo(returnMoneyVO.getArriveMoney()) != 0){
            return (ResponseCodeEnum.UPDATE_RETURN_MONEY_MAX.getResponseCode());
        }
        //获取订单信息
        CustomerProductOrderVO order = productOrderDbService.getOrderInfoById(returnMoney.getOrderId());
        String orderStatus = order.getOrderStatus();
        BigDecimal gradeMoney = finishOrderDBservice.selectGradeMoneyByOrderId(order.getProductOrderId());
        CustomerContract contract=contractDbService.selectContractById(order.getContractId());
        if(Objects.nonNull(returnMoney.getReturnMoneyId())) {
            //根据id查询回款信息
            if (Objects.isNull(returnMoneyVO.getArriveMoney())){
                returnMoneyVO.setArriveMoney(new BigDecimal("0.00"));
            }
            order.setUpdatePeopleId(user.getAccountId());
            order.setUpdateTm(new Date());
            order.setPaidBackAmount(order.getPaidBackAmount().subtract(returnMoneyVO.getArriveMoney()).add(returnMoney.getArriveMoney()));
            returnMoney.setFilialeId(order.getAffiliationCompanyId());

            if (!returnMoneyVO.getArriveMoney().equals(returnMoney.getArriveMoney())){
                returnMoney.setScoreMoney(returnMoney.getArriveMoney().divide(returnMoneyVO.getScoreConvertRatio()));
            }
            if (order.getPaidBackAmount().toString().equals(contract.getContractReceivables().toString())) {
                if (!"2".equals(order.getOrderStatus())){
                    order.setOrderStatus("2");
                    order.setOrderCompleteTm(new Date());
                }
                //更新订单表
                productOrderDbService.updateOrderComplete(order);
                //更新合同
                contract = updateCustomerContract(returnMoney,order,2);

            }else{
                if (!order.getPaidBackAmount().toString().equals(contract.getContractReceivables().toString())){
                    //状态回退到部分回款状态
                    order.setOrderStatus("4");
                    order.setOrderCompleteTm(null);
                }
                //更新订单表
                productOrderDbService.updateOrderComplete(order);
                //更新合同
                contract = updateCustomerContract(returnMoney,order,2);
            }
            returnMoneyDbservice.updateReturnMoney(returnMoney);

            StringBuilder sb = new StringBuilder();
            StringBuilder newSb = new StringBuilder();
            if (returnMoney.getArriveTime().getTime() != returnMoneyVO.getArriveTime().getTime()){
                sb.append("到款日期："+DateUtil.formatDateTime(returnMoneyVO.getArriveTime())+"；");
                newSb.append("到款日期："+DateUtil.formatDateTime(returnMoney.getArriveTime())+"；");
            }
            if (!returnMoney.getArriveMoney().toString().equals(returnMoneyVO.getArriveMoney().toString())){
                sb.append("金额："+returnMoneyVO.getArriveMoney()+"；");
                newSb.append("金额："+returnMoney.getArriveMoney()+"；");
                FinishOrderProduct finish = finishOrderDBservice.selectFinishOrderProductById(returnMoneyVO.getFinishOrderProductId());
                finish.setGradeMoney(finish.getGradeMoney().subtract(returnMoneyVO.getScoreMoney()).add(returnMoney.getScoreMoney()));
                BigDecimal big = returnMoneyDbservice.selectOrderProductReturnMoneyCount(finish.getFinishOrderProductId(),finish.getProductOrderId());
                if (Objects.isNull(big)){
                    big = new BigDecimal("0");
                }
                if (big.compareTo(finish.getProductFinalPrice()) == 0){
                    finish.setProductStatus("3");
                }else if (new BigDecimal("0").compareTo(big) == 0){
                    finish.setProductStatus("0");
                }else if (finish.getProductFinalPrice().compareTo(big) == 1){
                    finish.setProductStatus("2");
                }
                //修改finish
                finishOrderDBservice.updateFinishOrderProduct(finish);
            }
            if (!returnMoney.getPaymentUnit().equals(returnMoneyVO.getPaymentUnit())){
                sb.append("付款单位："+returnMoneyVO.getPaymentUnit()+"；");
                newSb.append("付款单位："+returnMoney.getPaymentUnit()+"；");
            }
            if (!returnMoney.getArriveMethod().equals(returnMoneyVO.getArriveMethod())){
                sb.append("支付方式："+arriveMethod(returnMoneyVO.getArriveMethod())+"；");
                newSb.append("支付方式："+arriveMethod(returnMoney.getArriveMethod())+"；");
            }
            if (!returnMoney.getPaymentAccount().equals(returnMoneyVO.getPaymentAccount())){
                sb.append("付款账号："+returnMoneyVO.getPaymentAccount()+"；");
                newSb.append("付款账号："+returnMoney.getPaymentAccount()+"；");
            }
            if (!returnMoney.getPaymentBank().equals(returnMoneyVO.getPaymentBank())){
                sb.append("付款银行："+returnMoneyVO.getPaymentBank()+"；");
                newSb.append("付款银行："+returnMoney.getPaymentBank()+"；");
            }
            if (!returnMoney.getSerial().equals(returnMoneyVO.getSerial())){
                sb.append("水流号："+returnMoneyVO.getSerial()+"；");
                newSb.append("水流号："+returnMoney.getSerial()+"；");
            }
            if (!returnMoney.getArriveUnitName().equals(returnMoneyVO.getArriveUnitName())){
                sb.append("到款单位："+returnMoneyVO.getArriveUnitName()+"；");
                newSb.append("到款单位："+returnMoney.getArriveUnitName()+"；");
            }
            if (Objects.isNull(returnMoneyVO.getRemark())){
                returnMoneyVO.setRemark("");
            }
            if (!returnMoney.getRemark().equals(returnMoneyVO.getRemark())){
                sb.append("备注："+returnMoneyVO.getRemark()+"；");
                newSb.append("备注："+returnMoney.getRemark()+"；");
            }
            //金额不一样更新修改记录
            if (StringUtils.isNotBlank(sb)){
                ReturnMoneyLog returnMoneyLog=new ReturnMoneyLog();
                returnMoneyLog.setCreatePeopleId(user.getAccountId());
                returnMoneyLog.setCreateTm(new Date());
                returnMoneyLog.setReturnMoneyId(returnMoney.getReturnMoneyId());
                returnMoneyLog.setReturnMoneyLogId(CommonUtils.getGUID());
                returnMoneyLog.setNewData(newSb.toString());
                returnMoneyLog.setFormerData(sb.toString());
                returnMoneyLog.setOperatorType(1);
                //回款修改记录
                returnMoneyLogDbService.addReturnMoneyLog(returnMoneyLog);
            }
            //查合同
            CustomerContractDetailVO contractInfo=contractDbService.selectCustomerContractVODetail(order.getContractId());
            AddFinishResultVO addFinishResultVO = new AddFinishResultVO();
            //订单完成同步chs_finish_order_product;循环三次，分别查询普通产品、活动产品、赠品产品
            if ("2".equals(order.getOrderStatus())){
                List<FinishOrderProduct> finishList=productOrderDbService.getFinishProductList(returnMoney.getOrderId());
                if (finishList.size() > 0){
                    addFinishResultVO = addFinishProductList(finishList,0,contractInfo.getContractType(),returnMoney,2);
                    //判断原来订单是否完成 完成的话走这个接口 没完成走 add 接口
                    if ("2".equals(orderStatus)){
                        returnMoneyRedisService.updateReturnMoneyToRedis(addFinishResultVO.getGradeMoney(),returnMoney.getFilialeId(),returnMoney.getArriveMoney(),returnMoney.getArriveTime(),returnMoneyVO.getArriveMoney(),returnMoneyVO.getArriveTime());
                    }else {
                        returnMoneyRedisService.returnMoneyToRedis(returnMoney.getFilialeId(),addFinishResultVO.getGradeMoney(),returnMoney.getArriveMoney(),returnMoney.getArriveTime());
                    }
                }
                //维护客户表会员到期时间、会员开始时间、客户状态、会员等级
                // 2、4为会员合同
                if ("2".equals(contract.getContractType()) || "4".equals(contract.getContractType())){
                    updateCustomer(contract);
                }
                //全部完成插入一条消息
                messagePromptDbService.insertMsg(contract,1);
            }else if ("2".equals(orderStatus)){
                Date arriveTime = returnMoneyDbservice.selectOrderMaxArriveTime(order.getProductOrderId());
                //原来是完成状态，修改后订单状态不是完成。
                returnMoneyRedisService.delReturnMoney(arriveTime,returnMoney.getFilialeId(),new BigDecimal("0"),gradeMoney);
                returnMoneyRedisService.delReturnMoney(returnMoneyVO.getArriveTime(),returnMoney.getFilialeId(),returnMoneyVO.getArriveMoney(),new BigDecimal("0"));
            }
        }
        return (ResponseCodeEnum.OK.getResponseCode());
    }

    /**
     *
     * @param returnMoney 回款信息
     * @param dataSourceType 0-正常录入，1-导入
     * @param preReturnMoneyFlag 是否是预回款
     * @return
     * @throws ParseException
     */
    @Override
    public Map<String,Object> mergeAddReturnMoneyMethod(ReturnMoney returnMoney,Integer dataSourceType,boolean preReturnMoneyFlag) throws ParseException {
        UserAccount user = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        Map<String,Object> map = new HashMap<>();
        //判断金额是否正常
        boolean b=ifReturnMoney(returnMoney);
        if (!b){
            map.put("code",ResponseCodeEnum.RNTURN_MONEY_TOOBIG.getResponseCode());
            return map;
        }
        if (returnMoney.getArriveType() == 1){
            //查询产品回款金额含预回款
            BigDecimal big = returnMoneyDbservice.selectOrderProductReturnMoneyAllCount(returnMoney.getFinishOrderProductNum(),returnMoney.getOrderId());
            big = big.add(returnMoney.getArriveMoney());
            FinishOrderProductVO vo = new FinishOrderProductVO();
            if ("0001".equals(returnMoney.getFinishOrderProductNum())){
                CustomerProductOrder order = productOrderDbService.selectProductOrderById(returnMoney.getOrderId());
                vo.setProductFinalPrice(order.getOrderSurcharge());
            }
            if (!"0001".equals(returnMoney.getFinishOrderProductNum())){
                vo = finishOrderProductDbService.selectFinishOrderProductByNumber(returnMoney.getFinishOrderProductNum());
            }
            if (Objects.isNull(vo.getProductFinalPrice())){   //产品成交价正常情况下不能为空
                map.put("code",ResponseCodeEnum.PARAMETER_MISSING.getResponseCode());
                return map;
            }
            if (vo.getProductFinalPrice().compareTo(big) == -1){
                map.put("code",ResponseCodeEnum.PRODUCT_RNTURN_MONEY_TOOBIG.getResponseCode());
                return map;
            }
        }
        //判断合同状态是否正常
        b=contractReviewStatus(returnMoney);
        if (!b){
            map.put("code",ResponseCodeEnum.RNTURN_MONEY_REVIEW.getResponseCode());
            return map;
        }
        //订单是否作废
        b=orderIfAbolish(returnMoney);
        if (!b){
            map.put("code",ResponseCodeEnum.RNTURN_MONEY_ABOLISH.getResponseCode());
            return map;
        }
        //到款时间
        b=Integer.valueOf(DateUtil.formatDateTime(returnMoney.getArriveTime()).substring(0,10).replaceAll("-","")) <= Integer.valueOf(DateUtils.getToday().replaceAll("-",""));
        if (!b){
            map.put("code",ResponseCodeEnum.RNTURN_MONEY_TIME_ERROR.getResponseCode());
            return map;
        }
        CustomerProductOrder order = productOrderDbService.selectProductOrderById(returnMoney.getOrderId());
        if (returnMoney.getArriveType() == 1 && "1".equals(order.getContractOtherType())){
            map.put("code",ResponseCodeEnum.RETURN_MONEY_BKSJ_ALL.getResponseCode());
            return map;
        }
        map = addReturnMoney(returnMoney,dataSourceType,preReturnMoneyFlag);


        //发放会员卡
        hairpin(returnMoney.getOrderId());

        return map;
    }

    /**
     * 统计业务员每月的业绩
     */
    @Override
    public void getSalesmanResultsByMonth() {
        Set<String> list = new HashSet<>();
        List<SalesmanDto> dtos = returnMoneyDbservice.getSalesmanResultsByMonth();
        if (dtos!=null && dtos.size()>0){
            for(SalesmanDto sa : dtos) {
                list.add(sa.getArriveTime());
            }
        }
        for(String date :list ) {
            List<SalesmanDto> dList = new ArrayList<>();
            for(SalesmanDto sa : dtos){
                if(date.equals(sa.getArriveTime())) {
                    dList.add(sa);
                }
            }
            String key = RedisPrefix.SALESMAN_MONTH + date;
            ValueRMapper.setRedisString(redisTemplate, key, JSON.toJSONString(dList));
        }

    }

    /**
     * 统计业务员每年的业绩
     */
    @Override
    public void getSalesmanResultsByYear() {

        Set<String> list = new HashSet<>();
        List<SalesmanDto> dtos = returnMoneyDbservice.getSalesmanResultsByYear();
        if (dtos!=null && dtos.size()>0){
            for(SalesmanDto sa : dtos) {
                list.add(sa.getArriveTime());
            }
        }
        for(String date :list ) {
            List<SalesmanDto> dList = new ArrayList<>();
            for(SalesmanDto sa : dtos){
                if(date.equals(sa.getArriveTime())) {
                    dList.add(sa);
                }
            }
            String key = RedisPrefix.SALESMAN_YEAR + date;
            ValueRMapper.setRedisString(redisTemplate, key, JSON.toJSONString(dList));
        }
    }


    /**
     * 回款完成发放会员卡
     * @param orderId 订单id
     */
    @Override
    public void hairpin(String orderId) throws ParseException {
        UserAccount user = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息

        CustomerProductOrderVO order = productOrderDbService.getOrderInfoById(orderId);
        //查询订单是否发过会员码
        CustomerProductOrder o = productOrderDbService.selectProductOrderAndSendStatus(order.getProductOrderId(), 1);

        if (o == null) {
            if (order.getOrderCompleteTm() != null) {
                List<FinishOrderProduct> list = finishOrderProductDbService.selectCustomerProductListByOrderId(order.getProductOrderId(), "1");
                if (list.size() > 0) {
                    for (FinishOrderProduct detail : list) {
                        if(detail.getProductFinalPrice() != null) {
                            reqCrm(order,detail.getProductCode(),"1",detail.getProductFinalPrice(),user,detail.getFinishOrderProductNum());
                        }else{
                            reqCrm(order,detail.getProductCode(),"1",new BigDecimal(0.0),user,detail.getFinishOrderProductNum());
                        }
                    }
                    CustomerProductOrder productOrder = new CustomerProductOrder();
                    productOrder.setProductOrderId(order.getProductOrderId());
                    productOrder.setUpdatePeopleId(user.getAccountId());
                    productOrder.setUpdateTm(new Date());
                    productOrder.setExchangeCodeSendingStatus(1);
                    productOrderDbService.updateProductOrder(productOrder);
                }

            }
        }
    }

    /**
     *访问crm系统接收发卡信息
     * @param order 订单
     * @param productCode 产品编码
     * @param productQuantity 数量
     * @param productFinalPrice 成交价
     */
    @Override
    public String reqCrm(CustomerProductOrderVO order,String productCode,String productQuantity,BigDecimal productFinalPrice,UserAccount user,String finishOrderProductNum) {


        ReturnMoneyVO returnMoney = returnMoneyDbservice.selectReturnMoneyByOrderId(order.getProductOrderId());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String da = "";
        String beginTime = "2021-08-01 00:00:00";
        if(returnMoney != null) {
            if(returnMoney.getArriveTime() != null) {
                da = sdf.format(returnMoney.getArriveTime());
            }
        }
        //String da = sdf.format(returnMoney.getArriveTime());
        Date date1 = null;
        Date date2 = null;
        try{
            date1 = sdf.parse(beginTime);
            if(!StringUtils.isBlank(da)) {
                date2 = sdf.parse(da);
            }
        }catch(Exception e) {
            e.printStackTrace();
        }


        //小于
        if(date2 != null) {
            if(date1.compareTo(date2) == -1) {
                String rs = specificSendCode(productCode, productQuantity, da, finishOrderProductNum, productFinalPrice, order, user);
                return rs;
            }else{
                return "{\"code\":0,\"msg\":\"2021年8月1号之前的不发码\",\"data\":[]}";
            }
        }else{
            String rs = specificSendCode(productCode,productQuantity,da, finishOrderProductNum,productFinalPrice,order,user);
            return rs;
        }

    }

    /**
     * 发码
     * @param productCode 产品编码
     * @param productQuantity 产品数量
     * @param da 到款时间
     * @param finishOrderProductNum 产品号
     * @param productFinalPrice 成交价
     * @param order 订单
     * @param user 用户
     * @return
     */
    public String specificSendCode(String productCode, String productQuantity, String da, String finishOrderProductNum, BigDecimal productFinalPrice,CustomerProductOrderVO order,UserAccount user) {

        SysCompany sysCompany = sysCompanyDbService.selectSysCompanyById(user.getCompanyId());

        Customer customer = customerDbService.selectCustomerById(order.getCustomerId());

        CustomerContract contract = contractDbService.selectContractById(order.getContractId());


        String url = "http://api.nsrjlb.com/crm/ExchangeCode/distributeCard";

        //产品编码 例：67|1,67_11|2（产品编码|产品数量,产品编码|产品数量）
        String req = "code=" + productCode + "|" + productQuantity;

        //到款日期
        if(!StringUtils.isBlank(da)) {
            req += "&fdata=" + da;
        }else{
            req += "&fdata=" + "2021-08-02";
        }
        //req += "&id=" + order.getProductOrderId();

        //产品号
        req += "&id=" + finishOrderProductNum;

        //到款金额
        //req += "&price=" + order.getOrderActualTotalAmount();
        if(productFinalPrice != null) {
            req += "&price=" + productFinalPrice;
        }else{
            req += "&price=" + new BigDecimal("0.0");
        }


        //客户名称
        if (!StringUtils.isBlank(customer.getCustomerName())) {
            req += "&firm=" + customer.getCustomerName();
        } else {
            req += "&firm=";
        }

        //公司id
        if (sysCompany != null) {
            req += "&pid=" + sysCompany.getCompanyCode();
        } else {
            req += "&pid=";
        }

        //联系人名称
        if (!StringUtils.isBlank(contract.getContactName())) {
            req += "&contactName=" + contract.getContactName();
        } else {
            req += "&contactName=";
        }

        //手机号
        if (!StringUtils.isBlank(contract.getContactDetails())) {
            req += "&mobile=" + contract.getContactDetails();
        } else {
            req += "&mobile=";
        }

        //订单编号
        req += "&orderNumber=" + order.getOrderNumber();

        //合同开始日期
        req +="&contractStartDate=" + contract.getContractStartDate();

        //支付方式
        if(!StringUtils.isBlank(contract.getPaymentMethod())) {
            req +="&paymentMethod=" + contract.getPaymentMethod();
        }


        log.info("请求数据---"+req);
        String res = post(url, req);
        log.info("返回数据---"+res);
        if (res != null) {
            JSONObject json = JSON.parseObject(res);
            Integer de = json.getInteger("code");
            if (de != null && de == 1) {
                JSONObject jsonObj = json.getJSONObject("data");//获取json数组中的data项

                //兑换码
                String exchangeCode = jsonObj.getString("exchangeCode");
                if (!StringUtils.isBlank(exchangeCode)) {
                    List<ExchangeCodeVO> exList = JSONArray.parseArray(exchangeCode, ExchangeCodeVO.class);
                    for (ExchangeCodeVO exchange : exList) {
                        CustomerProductDetailExchangeCode ex = new CustomerProductDetailExchangeCode();
                        ex.setExchangeCodeId(CommonUtils.getGUID());
                        ex.setExchangeCodeCrmId(exchange.getPromotionCode());
                        ex.setExchangeCodeName(exchange.getPromotionName());
                        ex.setExchangeCodePassword(exchange.getPassword());
                        ex.setCreatePeopleId(user.getAccountId());
                        ex.setCreateTm(new Date());
                        ex.setUpdatePeopleId(user.getAccountId());
                        ex.setUpdateTm(new Date());
                        ex.setProductOrderId(order.getProductOrderId());
                        ex.setProductCode(productCode);
                        ex.setFinishOrderProductNum(finishOrderProductNum);
                        customerDbService.addCustomerProductDetailExchangeCode(ex);
                    }
                }

                //税法直通车
                String throughTrain = jsonObj.getString("throughTrain");
                if (!StringUtils.isBlank(throughTrain)) {
                    List<ThroughTrainVO> array2 = JSONArray.parseArray(throughTrain, ThroughTrainVO.class);
                    for (ThroughTrainVO vo : array2) {
                        CustomerProductDetailThroughTrainTax customerProductDetailThroughTrainTax = new CustomerProductDetailThroughTrainTax();
                        customerProductDetailThroughTrainTax.setThroughTrainTaxId(CommonUtils.getGUID());
                        customerProductDetailThroughTrainTax.setThroughTrainTaxCrmId(vo.getUserid());
                        customerProductDetailThroughTrainTax.setMemberCardNumber(vo.getUsername());
                        customerProductDetailThroughTrainTax.setMemberCardPassword(vo.getPassword());
                        customerProductDetailThroughTrainTax.setCreatePeopleId(user.getAccountId());
                        customerProductDetailThroughTrainTax.setCreateTm(new Date());
                        customerProductDetailThroughTrainTax.setUpdatePeopleId(user.getAccountId());
                        customerProductDetailThroughTrainTax.setUpdateTm(new Date());
                        customerProductDetailThroughTrainTax.setProductOrderId(order.getProductOrderId());
                        customerProductDetailThroughTrainTax.setProductCode(productCode);
                        customerProductDetailThroughTrainTax.setFinishOrderProductNum(finishOrderProductNum);
                        customerDbService.addCustomerProductDetailThroughTrainTax(customerProductDetailThroughTrainTax);
                    }
                }
                String customerProductDetailMemberCardId = CommonUtils.getGUID();
                String number = "";
                //会员卡
                String userInfo = jsonObj.getString("userInfo");
                if (!StringUtils.isBlank(userInfo)) {
                    List<CustomerCardVO> customerCardList = JSONArray.parseArray(userInfo, CustomerCardVO.class);
                    CustomerContract customerContract = contractDbService.selectContractById(order.getContractId());
                    for (CustomerCardVO customerCardVO : customerCardList) {
                        CustomerProductDetailMemberCard customerProductDetailMemberCard = new CustomerProductDetailMemberCard();

                        customerProductDetailMemberCard.setCustomerProductDetailMemberCardId(customerProductDetailMemberCardId);
                        customerProductDetailMemberCard.setMemberProductCode(productCode);
                        customerProductDetailMemberCard.setMemberCardId(customerCardVO.getUserid()); //crm的id
                        number = customerCardVO.getUsername();
                        customerProductDetailMemberCard.setMemberCardNumber(customerCardVO.getUsername());
                        customerProductDetailMemberCard.setMemberCardPassword(customerCardVO.getPassword());
                        customerProductDetailMemberCard.setStartTm(customerCardVO.getRuhuidata());
                        customerProductDetailMemberCard.setEndTm(customerCardVO.getYouxiaodata());
                        customerProductDetailMemberCard.setProductPrice(productFinalPrice);
                        customerProductDetailMemberCard.setCreatePeopleId(user.getAccountId());
                        customerProductDetailMemberCard.setCreateTm(new Date());
                        customerProductDetailMemberCard.setUpdatePeopleId(user.getAccountId());
                        customerProductDetailMemberCard.setUpdateTm(new Date());
                        customerProductDetailMemberCard.setAccountId(user.getAccountId());
                        customerProductDetailMemberCard.setCustomerId(order.getCustomerId());
                        customerProductDetailMemberCard.setContractId(order.getContractId());
                        customerProductDetailMemberCard.setContractNumber(customerContract.getContractNumber());
                        customerProductDetailMemberCard.setProductOrderId(order.getProductOrderId());
                        customerProductDetailMemberCard.setOrderNumber(order.getOrderNumber());
                        customerProductDetailMemberCard.setContactName(contract.getContactName());
                        customerProductDetailMemberCard.setPhone(contract.getContactDetails());
                        customerProductDetailMemberCard.setCompanyId(user.getCompanyId());
                        customerProductDetailMemberCard.setFinishOrderProductNum(finishOrderProductNum);
                        customerProductDetailMemberCard.setMaster(customerCardVO.getMaster());
                        customerDbService.addCustomerProductDetailMemberCard(customerProductDetailMemberCard);
                    }
                }
                if(!StringUtils.isBlank(number)) {
                    csdCustomerServiceImpl.getCardFrequency(number,customerProductDetailMemberCardId);
                }



                //云顾问卡
                String yunK = jsonObj.getString("user_yun");
                if (!StringUtils.isBlank(yunK)) {
                    List<YunVO> yunList = JSONArray.parseArray(yunK, YunVO.class);
                    for (YunVO Y : yunList) {
                        CustomerProductDetailYun yun = new CustomerProductDetailYun();
                        yun.setYunId(CommonUtils.getGUID());
                        yun.setYunCrmId(Y.getId());
                        yun.setYunCard(Y.getCard());
                        yun.setYunPassword(Y.getPassword());
                        yun.setCreatePeopleId(user.getAccountId());
                        yun.setCreateTm(new Date());
                        yun.setUpdatePeopleId(user.getAccountId());
                        yun.setUpdateTm(new Date());
                        yun.setProductOrderId(order.getProductOrderId());
                        yun.setProductCode(productCode);
                        yun.setFinishOrderProductNum(finishOrderProductNum);
                        customerDbService.addCustomerProductDetailYun(yun);
                    }
                }

                //充值卡
                String rechargeCode = jsonObj.getString("rechargeCode");
                if (!StringUtils.isBlank(rechargeCode)) {
                    List<RechargeCodeVO> exList = JSONArray.parseArray(rechargeCode, RechargeCodeVO.class);
                    for (RechargeCodeVO recharge : exList) {
                        CustomerProductDetailRechargeCode ex = new CustomerProductDetailRechargeCode();
                        ex.setRechargeCodeId(CommonUtils.getGUID());
                        ex.setRechargeCodeCrmId(recharge.getRechargeCode());
                        ex.setRechargeCodeName(recharge.getRechargeName());
                        ex.setRechargeCodePassword(recharge.getPassword());
                        ex.setCreatePeopleId(user.getAccountId());
                        ex.setCreateTm(new Date());
                        ex.setUpdatePeopleId(user.getAccountId());
                        ex.setUpdateTm(new Date());
                        ex.setProductOrderId(order.getProductOrderId());
                        ex.setProductCode(productCode);
                        ex.setFinishOrderProductNum(finishOrderProductNum);
                        customerDbService.addCustomerProductDetailRechargeCode(ex);
                    }
                }

                //优惠券
                String coupon = jsonObj.getString("coupon");
                if (!StringUtils.isBlank(coupon)) {
                    List<CouponVO> exList = JSONArray.parseArray(coupon, CouponVO.class);
                    for (CouponVO couponVO : exList) {
                        CustomerProductDetailCoupon c = new CustomerProductDetailCoupon();
                        c.setCouponId(CommonUtils.getGUID());
                        c.setCouponCodeCrmId(couponVO.getPromotionCode());
                        c.setCouponName(couponVO.getPromotionName());
                        if(!StringUtils.isBlank(couponVO.getPrice())) {
                            c.setPrice(couponVO.getPrice());
                        }
                        if(!StringUtils.isBlank(couponVO.getAbleproduct())) {
                            c.setAbleproduct(couponVO.getAbleproduct());
                        }
                        c.setCreatePeopleId(user.getAccountId());
                        c.setCreateTm(new Date());
                        c.setUpdatePeopleId(user.getAccountId());
                        c.setUpdateTm(new Date());
                        c.setProductOrderId(order.getProductOrderId());
                        c.setProductCode(productCode);
                        c.setFinishOrderProductNum(finishOrderProductNum);
                        customerDbService.addCustomerProductDetailCoupon(c);
                    }
                }

            }
            return res;
        }else{
            return res;
        }
    }

    /**
     * 查询退款统计信息
     * @param returnMoneyQO
     * @param pageIndex 页码
     * @param pageSize 条数
     * @param sortName 分组名称
     * @param sortOrder 分组类型
     * @return
     */
    @Override
    public DhPageInfo<CustomerOrderBackMoneyVO> selectOrderBackMoney(ReturnMoneyQO returnMoneyQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(returnMoneyQO.getDateType())) {
            if ("thisWeek".equals(returnMoneyQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(returnMoneyQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(returnMoneyQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
            if ("topDay".equals(returnMoneyQO.getDateType())) {
                //昨天
                dateUnit = 4;
            }
            if ("day".equals(returnMoneyQO.getDateType())) {
                //今天
                dateUnit = 5;
            }
        }
        returnMoneyQO.setCompanyId(userAccount.getCompanyId());
        List<CustomerOrderBackMoneyVO> returnMoneyVOList= new ArrayList<>();
        if("1".equals(returnMoneyQO.getCollectionType())) {
            returnMoneyVOList = returnMoneyDbservice.selectPartOrderBackMoney(returnMoneyQO,dateUnit);
        }else {
            returnMoneyVOList = returnMoneyDbservice.selectDoneOrderBackMoney(returnMoneyQO,dateUnit);
        }

        PageInfo<CustomerOrderBackMoneyVO> pageInfo = new PageInfo<CustomerOrderBackMoneyVO>(returnMoneyVOList);
        return new DhPageInfo<CustomerOrderBackMoneyVO>(pageInfo, returnMoneyVOList);
    }

    @Override
    public boolean exportReturnMoneyList(ReturnMoneyQO returnMoneyQO, HttpServletResponse response) throws IOException {
        DhPageInfo<ReturnMoneyVO> returnMoneyVODhPageInfo = selectCustomerProductList(returnMoneyQO, null, null, "createTm", null);
        List<ReturnMoneyVO> returnMoneyList = returnMoneyVODhPageInfo.getList();
        List<ReturnMoneyExportModel> returnMoneyExportModelList = new ArrayList<>();
        if(returnMoneyList==null || returnMoneyList.size()<=0){
            return false;//查询结果为空
        }
        for(ReturnMoneyVO returnMoneyVO : returnMoneyList){
            ReturnMoneyExportModel model = new ReturnMoneyExportModel();
            //到款方式 0银行汇款 1现金
            if(returnMoneyVO.getArriveMethod()!=null){
                if(returnMoneyVO.getArriveMethod() == 0){
                    model.setArriveMethodName("银行汇款");
                }else if(returnMoneyVO.getArriveMethod() == 1){
                    model.setArriveMethodName("现金");
                }
            }
            BeanUtils.copyProperties(returnMoneyVO,model);
            returnMoneyExportModelList.add(model);
        }
        Map map = new HashMap<>();
        map.put("回款记录",returnMoneyExportModelList);
        EasyExcelUtil.writeExcel(map,response.getOutputStream());
        return true;
    }

    /**
     * 订单回款错误关联
     * @param orderId
     * @param shiftOrderNumber
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public String shiftOrderReturnMoney(String orderId, String shiftOrderNumber,String finishId,Integer type,BigDecimal returnMoneyBig) {
        //ReturnMoneyVO returnMoneyVO = returnMoneyDbservice.selectReturnMoneyById(returnMoneyId);
        List<ReturnMoneyVO> returnMoneyList = null;returnMoneyDbservice.selectOrderId(orderId);
        if (0 == type){
            returnMoneyList = returnMoneyDbservice.selectOrderId(orderId);
        }
        CustFinanceProductOderVO oldFinish = null;
        CustomerProductOrderVO shiftOrderVO = productOrderDbService.selectOrderByNumber(shiftOrderNumber);
        if (1 == type){
            if ("1".equals(shiftOrderVO.getContractOtherType())){ //补款升级合同只能全额回款
                return (ResponseCodeEnum.RETURN_MONEY_BKSJ_ALL.getResponseCode());
            }
            FinishOrderProduct finishOrderProduct = finishOrderDBservice.selectFinishOrderProductById(finishId);
            List<CustFinanceProductOderVO> list = finishOrderDBservice.selectFinishOrderProductByProductId(finishOrderProduct.getProductId(),orderId);
            for (int i=0;i>list.size();i++){
                if ("3".equals(list.get(i).getProductStatus()) && returnMoneyBig.compareTo(list.get(i).getProductFinalPrice()) != 1){
                    oldFinish = list.get(i);
                }else if ("2".equals(list.get(i).getProductStatus())){
                    BigDecimal big= returnMoneyDbservice.selectOrderProductReturnMoneyCount(list.get(i).getFinishOrderProductId(),orderId);
                    if (returnMoneyBig.compareTo(big) != 1){
                        oldFinish = list.get(i);
                    }
                }
                if (Objects.nonNull(oldFinish)){
                    break;
                }
            }
            returnMoneyList = returnMoneyDbservice.selectReturnMoneyByFinishId(finishId);
        }

        CustomerContract shiftContract = contractDbService.selectContractByOrderId(shiftOrderVO.getProductOrderId());
        if (Objects.isNull(returnMoneyList) || returnMoneyList.size() == 0){
            return (ResponseCodeEnum.ORDER_RETURN_MONEY_EXIST.getResponseCode());
        }
        if (Objects.isNull(shiftOrderVO) || Objects.isNull(shiftOrderVO.getProductOrderId())){
            return (ResponseCodeEnum.SHIFT_ORDER_EXIST.getResponseCode());
        }
        if (!"1".equals(shiftOrderVO.getOrderStatus())){//已回款
            //return (ResponseCodeEnum.ORDER_STATUS_RETURN_MONEY_EXIST.getResponseCode());
        }
        CustomerContract contract = contractDbService.selectContractById(shiftOrderVO.getContractId());
        CustomerProductOrder order = productOrderDbService.selectProductOrderById(orderId);
        if (order.getOrderNumber().equals(shiftOrderNumber)){
            return (ResponseCodeEnum.SHIFT_RETURN_MONEY_EQUALS.getResponseCode());
        }
        if (0 == type && !order.getPaidBackAmount().equals(contract.getContractReceivables())){
            return (ResponseCodeEnum.SHIFT_RETURN_MONEY_NOT_MATCHING.getResponseCode());
        }

        for (int i=0;i<returnMoneyList.size();i++){
            if (1 == returnMoneyList.get(i).getShiftType() && 0 == type){
                return (ResponseCodeEnum.SHIFT_RETURN_MONEY_EXIST.getResponseCode());
            }
            if (1 == type && 1 == returnMoneyList.get(i).getShiftType()){
                return (ResponseCodeEnum.SHIFT_RETURN_MONEY_EXIST.getResponseCode());
            }

        }

        List<CustomerOrderInvoice> orderInvoice = customerOrderInvoiceDbService.selectOrderInvoiceByOrderId(orderId);
        if (Objects.nonNull(orderInvoice) && orderInvoice.size() > 0){
            return (ResponseCodeEnum.ORDER_RETURN_MONEY_INVOICE_EXIST.getResponseCode());
        }
        BigDecimal royaltyMoney = finishOrderDBservice.selectFinishOrderProductRoyaltyMoneyCountByOrderId(orderId);
        if(new BigDecimal("0").compareTo(royaltyMoney) > 0 ){
            return (ResponseCodeEnum.ORDER_RETURN_MONEY_ROYALTY_EXIST.getResponseCode());
        }
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        if (type == 0){
            BigDecimal paidMoney = order.getPaidBackAmount();
            List<ReturnMoney> shiftReturnMoneyLis = new ArrayList<>();
            List<ReturnMoney> returnMonies = returnMoneyDbservice.selectMoneyByOrderId(orderId);
            List<FinishOrderProduct> finishOrderProductList = finishOrderDBservice.selectFinishOrderProductList(null,shiftOrderVO.getProductOrderId());
            for (int i=0;i<returnMonies.size();i++){
                shiftReturnMoneyLis.add(returnMonies.get(i));
            }
            //finishOrderDBservice.selectFinish  查出finish表数据
            if (Objects.isNull(order.getPaidBackAmount())){
                order.setPaidBackAmount(new BigDecimal("0"));
            }
            Date paymentDate = null;
            String paymentAccount = null;
            BigDecimal big = new BigDecimal("0");
            int j = 0;
            for (int k=0;k<finishOrderProductList.size();k++){
                ReturnMoney returnMoney = null;
                big = finishOrderProductList.get(k).getProductFinalPrice();
                BigDecimal b = new BigDecimal("0");
                for (int l = j;l<returnMoneyList.size();l++){
                    b = returnMoneyList.get(l).getArriveMoney();
                    returnMoney =  new ReturnMoney();
                    returnMoney.setArriveType(0);
                    returnMoney.setArriveNum("GRM"+new Date().getTime());
                    returnMoney.setCustomerId(returnMoneyList.get(l).getCustomerId());
                    returnMoney.setFilialeId(returnMoneyList.get(l).getFilialeId());
                    returnMoney.setSalesmanId(returnMoneyList.get(l).getSalesmanId());
                    returnMoney.setArriveMoney(b);
                    returnMoney.setArriveTime(returnMoneyList.get(l).getArriveTime());
                    returnMoney.setArriveUnitName(returnMoneyList.get(l).getArriveUnitName());
                    returnMoney.setArriveMethod(returnMoneyList.get(l).getArriveMethod());
                    returnMoney.setArriveAccountType(returnMoneyList.get(l).getArriveAccountType());
                    returnMoney.setPaymentUnit(returnMoneyList.get(l).getPaymentUnit());
                    returnMoney.setPaymentAccount(returnMoneyList.get(l).getPaymentAccount());
                    returnMoney.setPaymentBank(returnMoneyList.get(l).getPaymentBank());
                    returnMoney.setVipType(returnMoneyList.get(l).getVipType());
                    returnMoney.setIsRecordScore(returnMoneyList.get(l).getIsRecordScore());
                    returnMoney.setOrderId(shiftOrderVO.getProductOrderId());
                    returnMoney.setRemark(returnMoneyList.get(l).getRemark());
                    returnMoney.setCreateBy(returnMoneyList.get(l).getCreateBy());
                    returnMoney.setCreateTm(returnMoneyList.get(l).getCreateTm());
                    returnMoney.setDelFlag(returnMoneyList.get(l).getDelFlag());
                    returnMoney.setDataSource(returnMoneyList.get(l).getDataSource());
                    returnMoney.setMemberErrorData(returnMoneyList.get(l).getMemberErrorData());
                    returnMoney.setUpdateBy(returnMoneyList.get(l).getUpdateBy());
                    returnMoney.setUpdateTm(returnMoneyList.get(l).getUpdateTm());
                    returnMoney.setProductId(finishOrderProductList.get(k).getProductId());
                    returnMoney.setProductNumber(finishOrderProductList.get(k).getProductCode());
                    returnMoney.setFinishOrderProductId(finishOrderProductList.get(k).getFinishOrderProductId());
                    returnMoney.setFinishOrderProductNum(finishOrderProductList.get(k).getFinishOrderProductNum());
                    returnMoney.setProductName(finishOrderProductList.get(k).getProductName());
                    returnMoney.setProductCategories(finishOrderProductList.get(k).getProductCategories());
                    returnMoney.setOrderNumber(shiftOrderVO.getOrderNumber());
                    returnMoney.setContractId(contract.getContractId());
                    returnMoney.setContractNumber(contract.getContractNumber());
                    returnMoney.setOrderDetailType(finishOrderProductList.get(k).getOrderDetailType());
                    returnMoney.setCustomerName(contract.getCustomerName());
                    returnMoney.setContractType(contract.getContractType());
                    returnMoney.setCreateTm(new Date());
                    returnMoney.setCreateBy(userAccount.getAccountId());
                    returnMoney.setShiftType(1);
                    returnMoney.setShiftOrderId(orderId);
                    if (returnMoney.getArriveMoney().compareTo(big) == 0 || returnMoney.getArriveMoney().compareTo(big) == 1){
                        returnMoney.setArriveMoney(big);
                        countReturnMoneyScoreMoney(returnMoney,finishOrderProductList.get(k),contract,l);
                        returnMoneyList.get(l).setArriveMoney(b.subtract(big));
                        if (returnMoneyList.get(l).getArriveMoney().compareTo(new BigDecimal("0")) == 0){
                            j++;
                        }
                        if (returnMoney.getArriveMoney().compareTo(big) == 1 || returnMoney.getArriveMoney().compareTo(big) == 0){
                            big = new BigDecimal("0");
                        }
                    }else if (returnMoney.getArriveMoney().compareTo(big) == -1){
                        returnMoney.setArriveMoney(b);
                        countReturnMoneyScoreMoney(returnMoney,finishOrderProductList.get(k),contract,l);
                        big = big.subtract(returnMoney.getArriveMoney());
                        j++;
                        //returnMoneyList.get(l).setArriveMoney(big.subtract(returnMoney.getArriveMoney()));
                        //finishOrderProductList.get(k).setProductFinalPrice(big.subtract(returnMoney.getArriveMoney()));
                    }
                    finishOrderProductList.get(k).setProductStatus("2");
                    if (new BigDecimal("0").compareTo(big) == 0){
                        l = returnMoneyList.size();
                        finishOrderProductList.get(k).setProductStatus("3");
                    }
                    //计算业绩金额
                    if(Objects.isNull(finishOrderProductList.get(k).getPerformanceConversionRatio())){
                        finishOrderProductList.get(k).setGradeMoney(new BigDecimal("0"));
                    }else if (Objects.nonNull(finishOrderProductList.get(k).getGradeMoney())){
                        finishOrderProductList.get(k).setGradeMoney(finishOrderProductList.get(k).getGradeMoney().add(returnMoney.getArriveMoney().multiply(finishOrderProductList.get(k).getPerformanceConversionRatio()).divide(new BigDecimal("1"),2)));
                    }else {
                        finishOrderProductList.get(k).setGradeMoney(returnMoney.getArriveMoney().multiply(finishOrderProductList.get(k).getPerformanceConversionRatio()).divide(new BigDecimal("1"),2));
                    }
                    //countReturnMoneyScoreMoney(returnMoney,finishOrderProductList.get(k),contract,l);

                    if (Objects.isNull(paymentDate)){ //最后一次回款时间
                        paymentDate = returnMoney.getArriveTime();
                    }else if (paymentDate.getTime() < returnMoney.getArriveTime().getTime()){
                        paymentDate = returnMoney.getArriveTime();
                    }

                    paymentAccount = returnMoney.getPaymentAccount();
                    finishOrderProductList.get(k).setArriveTime(paymentDate);
                    finishOrderDBservice.updateFinishOrderProduct(finishOrderProductList.get(k));
                }
                //错误关联-补款升级订单
                if ("1".equals(shiftOrderVO.getContractOtherType())){
                    //升级之前的finish
                    FinishOrderProduct f = finishOrderDBservice.selectFinishOrderProductById(contract.getUpgradeRelateFinishProductId());
                    FinishOrderProduct finishOrderProduct = finishOrderProductList.get(k);
                    //两个产品业绩比例一样就不需要补第二条TRM的
                    if(finishOrderProduct.getPerformanceConversionRatio().compareTo(f.getPerformanceConversionRatio()) != 0){
                        returnMoney.setScoreConvertRatio(finishOrderProduct.getPerformanceConversionRatio().subtract(f.getPerformanceConversionRatio()));
                        if (new BigDecimal("0").compareTo(f.getProductFinalPrice()) == -1){
                            returnMoney.setScoreMoney(f.getProductFinalPrice().multiply(returnMoney.getScoreConvertRatio()));
                        }
                        finishOrderProduct.setPerformanceConversionRatio(returnMoney.getScoreConvertRatio());
                        returnMoney.setArriveMoney(null);
                        returnMoney.setArriveNum("TRM"+new Date().getTime());
                        returnMoney.setCreateTm(new Date());
                        returnMoney.setCreateBy(userAccount.getAccountId());
                        countReturnMoneyScoreMoney(returnMoney,finishOrderProduct,contract,null);
                        //作废原订单产品号
                        customerProductOrderService.backProduct(f.getProductOrderId(),f.getFinishOrderProductNum());
                    }
                }
            }
            //维护新订单
            CustomerProductOrder shiftOrder = productOrderDbService.selectProductOrderById(shiftOrderVO.getProductOrderId());
            //判断合同回款金额是否全部回款
            if (shiftOrder.getPaidBackAmount().toString().equals(contract.getContractReceivables().toString())){
                shiftOrder.setOrderStatus("2");
                shiftOrder.setOrderCompleteTm(new Date());
            }else {//部分回款
                shiftOrder.setOrderStatus("4");
            }
            shiftOrder.setPaidBackAmount(shiftContract.getContractReceivables());
            shiftOrder.setUpdatePeopleId(userAccount.getAccountId());
            shiftOrder.setUpdateTm(new Date());
            productOrderDbService.updateByPrimaryKeySelective(shiftOrder);

            //维护新合同
            if ("2".equals(shiftOrder.getOrderStatus())){
                contract.setContractStatus("2");
                contract.setPaymentStatus("1");
            }else if ("4".equals(shiftOrder.getOrderStatus())){
                contract.setContractStatus("1");
                contract.setPaymentStatus("3");
            }
            shiftContract.setPaymentDate(paymentDate);
            shiftContract.setPaymentAccount(paymentAccount);
            shiftContract.setContractTotalPaymentAmount(shiftOrder.getPaidBackAmount());
            shiftContract.setUpdatePeopleId(userAccount.getAccountId());
            shiftContract.setUpdateTm(new Date());
            contractDbService.updateCustomerContract(shiftContract);

            //维护旧合同
            CustomerContract oldContract = contractDbService.selectContractById(shiftOrderVO.getContractId());
            oldContract.setContractStatus("1");
            oldContract.setPaymentStatus("0");
            oldContract.setPaymentDate(null);
            oldContract.setPaymentNumber(0);
            oldContract.setContractTotalPaymentAmount(new BigDecimal("0"));
            oldContract.setUpdateTm(new Date());
            oldContract.setUpdatePeopleId(userAccount.getAccountId());
            contractDbService.updateByPrimaryKey(oldContract);

            //维护旧订单
            order.setOrderStatus("1");
            order.setPaidBackAmount(new BigDecimal("0"));
            order.setOrderCompleteTm(null);
            order.setUpdateTm(new Date());
            order.setUpdatePeopleId(userAccount.getAccountId());
            productOrderDbService.updateByPrimaryKey(order);

            //删除旧订单回款记录
            returnMoneyDbservice.delReturnMoneyByOrderId(order.getProductOrderId(),userAccount.getAccountId());

            //清空订单下finish表回款数据
            finishOrderDBservice.clearFinishReturnMoneyInfoByOrderId(order.getProductOrderId(),userAccount.getAccountId());
        }
        if (type == 1){
            if (oldFinish != null){
                BigDecimal b = new BigDecimal("0");//累计关联金额
                List<ReturnMoneyVO> list = returnMoneyDbservice.selectReturnMoneyByFinishId(oldFinish.getFinishOrderProductId());
                for (int k=0;k<list.size() && b.compareTo(returnMoneyBig) == -1;k++){
                    ReturnMoneyVO returnMoneyVO =list.get(k);
                    b = b.add(returnMoneyVO.getArriveMoney());
                    List<CustFinanceProductOderVO> products = finishOrderDBservice.selectFinishOrderProductByProductId(returnMoneyVO.getProductId(),shiftOrderVO.getProductOrderId());
                    CustFinanceProductOderVO finishVO = null;
                    for(int i=0;i<products.size();i++){
                        BigDecimal big = returnMoneyDbservice.selectOrderProductReturnMoneyCount(products.get(i).getFinishOrderProductId(),shiftOrderVO.getProductOrderId());
                        if (Objects.isNull(big)){
                            big = new BigDecimal("0");
                        }
                        if (big.add(returnMoneyVO.getArriveMoney()).compareTo(products.get(i).getProductFinalPrice()) != -1){
                            finishVO = products.get(i);
                            break;
                        }
                    }
                    ReturnMoney returnMoney = new ReturnMoney();
                    BeanUtils.copyProperties(returnMoneyVO,returnMoney);
                    returnMoney.setReturnMoneyId(CommonUtils.getGUID());
                    returnMoney.setArriveNum("GRM"+new Date());
                    returnMoney.setArriveMoney(returnMoneyBig);
                    returnMoney.setFinishOrderProductId(finishVO.getFinishOrderProductId());
                    returnMoney.setFinishOrderProductNum(finishVO.getFinishOrderProductNum());
                    returnMoney.setOrderId(shiftOrderVO.getProductOrderId());
                    returnMoney.setOrderNumber(shiftOrderVO.getOrderNumber());
                    returnMoney.setCustomerId(shiftOrderVO.getCustomerId());
                    returnMoney.setCustomerName(shiftOrderVO.getCustomerName());
                    returnMoney.setContractId(shiftContract.getContractId());
                    returnMoney.setContractNumber(shiftContract.getContractNumber());
                    returnMoney.setOrderDetailType(finishVO.getOrderDetailType());
                    returnMoney.setSalesmanId(shiftOrderVO.getProductOrderId());
                    returnMoney.setSalesmanId(shiftOrderVO.getAffiliationCompanyId());
                    returnMoney.setShiftType(1);
                    returnMoney.setShiftOrderId(orderId);
                    returnMoney.setShiftReturnMoneyId(returnMoneyVO.getReturnMoneyId());
                    returnMoney.setCreateTm(new Date());
                    returnMoney.setCreateBy(userAccount.getAccountId());
                    returnMoneyDbservice.addReturnMoney(returnMoney);

                    FinishOrderProduct finish = finishOrderDBservice.selectFinishOrderProductById(returnMoney.getFinishOrderProductId());
                    if (Objects.nonNull(finish)){
                        if (Objects.isNull(finish.getGradeMoney())){
                            finish.setGradeMoney(returnMoney.getScoreMoney().divide(returnMoney.getScoreConvertRatio()));
                        }else {
                            finish.setGradeMoney(finish.getGradeMoney().add(returnMoney.getScoreMoney().divide(returnMoney.getScoreConvertRatio())));
                        }
                        BigDecimal big = returnMoneyDbservice.selectOrderProductReturnMoneyCount(returnMoney.getFinishOrderProductId(),shiftOrderVO.getProductOrderId());
                        //判断回款金额，当前产品是否全部回款
                        if (returnMoney.getArriveMoney().compareTo(finish.getProductFinalPrice().subtract(big)) == 0){
                            finish.setProductStatus("3");
                        }else if (!new BigDecimal("0").equals(returnMoney.getArriveMoney())&& !new BigDecimal("0.00").equals(returnMoney.getArriveMoney())){
                            finish.setProductStatus("2");//产品金额不为0，并且回款完成
                        }
                        finish.setArriveTime(returnMoneyDbservice.selectOrderMaxArriveTime(returnMoney.getOrderId()));
                        finishOrderDBservice.updateFinishOrderProduct(finish);
                    }
                    CustomerProductOrder newOrder = productOrderDbService.selectProductOrderById(shiftOrderVO.getProductOrderId());
                    //填充订单表数据
                    if (Objects.nonNull(newOrder.getPaidBackAmount())){
                        newOrder.setPaidBackAmount(newOrder.getPaidBackAmount().add(returnMoney.getArriveMoney()));
                    }else {
                        newOrder.setPaidBackAmount(returnMoney.getArriveMoney());
                    }
                    //判断合同回款金额是否全部回款
                    if (newOrder.getPaidBackAmount().toString().equals(contract.getContractReceivables().toString())){
                        newOrder.setOrderStatus("2");
                        newOrder.setOrderCompleteTm(new Date());
                    }else {//部分回款
                        newOrder.setOrderStatus("4");
                    }
                    newOrder.setUpdateTm(new Date());
                    newOrder.setUpdatePeopleId(userAccount.getAccountId());
                    //更新订单表
                    productOrderDbService.updateProductOrder(newOrder);
                    BeanUtils.copyProperties(shiftOrderVO,newOrder);
                    //更新合同
                    contract = updateCustomerContract(returnMoney,shiftOrderVO,1);

                    //回滚操作
                    finish = finishOrderDBservice.selectFinishOrderProductById(returnMoneyVO.getFinishOrderProductId());
                    if (Objects.nonNull(finish)){
                        if (Objects.nonNull(finish.getGradeMoney())){
                            BigDecimal oldGradeMoney = returnMoneyVO.getArriveMoney().divide(finish.getPerformanceConversionRatio());
                            if (finish.getGradeMoney().subtract(oldGradeMoney).compareTo(new BigDecimal("0")) != -1){
                                finish.setGradeMoney(finish.getGradeMoney().subtract(oldGradeMoney));
                            }
                        }
                        if (new BigDecimal("0").compareTo(finish.getGradeMoney()) != 1){
                            finish.setArriveTime(null);
                        }
                        if (finish.getProductFinalPrice().subtract(returnMoneyVO.getArriveMoney()).compareTo(new BigDecimal("0")) != 1){
                            finish.setProductStatus("0");
                        }else {
                            finish.setProductStatus("2");
                        }
                        finish.setUpdateTm(new Date());
                        finish.setUpdatePeopleId(userAccount.getAccountId());
                    }
                    finishOrderDBservice.updateFinishOrderProductAll(finish);
                    if (order.getPaidBackAmount().subtract(returnMoney.getArriveMoney()).compareTo(new BigDecimal("0")) != 1){
                        order.setOrderStatus("1");
                    }else {
                        order.setOrderStatus("4");
                    }
                    order.setPaidBackAmount(order.getPaidBackAmount().subtract(returnMoney.getArriveMoney()));
                    order.setUpdateTm(new Date());
                    order.setUpdatePeopleId(userAccount.getAccountId());
                    productOrderDbService.updateByPrimaryKey(order);
                    CustomerContract oldContract = contractDbService.selectContractById(order.getContractId());
                    oldContract.setContractStatus("1");
                    if ("1".equals(order.getOrderStatus())){
                        oldContract.setPaymentDate(null);
                        oldContract.setContractTotalPaymentAmount(null);
                        oldContract.setPaymentStatus("0");
                    }else {
                        oldContract.setPaymentStatus("3");
                        oldContract.setContractTotalPaymentAmount(oldContract.getContractTotalPaymentAmount().subtract(returnMoney.getArriveMoney()));
                    }
                    oldContract.setUpdateTm(new Date());
                    oldContract.setUpdatePeopleId(userAccount.getAccountId());
                    contractDbService.updateByPrimaryKey(contract);

                    returnMoney = new ReturnMoney();
                    returnMoney.setReturnMoneyId(returnMoneyVO.getReturnMoneyId());
                    returnMoney.setDelFlag(1);
                    returnMoneyDbservice.updateReturnMoney(returnMoney);
                }
            }
        }
        return (ResponseCodeEnum.OK.getResponseCode());
    }


    /**
     *请求外部系统
     * @param urlStr
     * @param xmlInfo
     * @return
     */
    public String post(String urlStr, String xmlInfo) {
        String obj = null;

        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpPost httppost = new HttpPost(urlStr);
        httppost.addHeader("Content-type", "application/x-www-form-urlencoded");
        //httppost.setHeader("Accept", "application/json");
        try {
            StringEntity s = new StringEntity(xmlInfo, Charset.forName("UTF-8"));
            s.setContentEncoding("UTF-8");
            httppost.setEntity(s);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null)
                    obj = EntityUtils.toString(entity, "UTF-8");
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }

    /**
     * 修改合同
     * @param returnMoney 回款信息
     * @param order 订单信息
     * @param type 类型 1：录入回款 2：修改回款
     * @return
     */
    public CustomerContract updateCustomerContract(ReturnMoney returnMoney,CustomerProductOrderVO order,Integer type){
        UserAccount user = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        CustomerContract contract=contractDbService.selectContractById(order.getContractId());
        contract.setContractId(order.getContractId());
        contract.setContractTotalPaymentAmount(order.getPaidBackAmount());
        if (type == 1){
            //查询回款次数
            Integer returnMoneyNum=returnMoneyDbservice.getReturnMoneyNum(returnMoney.getContractId());
            contract.setPaymentNumber(returnMoneyNum);
        }
        //更新回款账号
        if (Objects.nonNull(returnMoney.getPaymentAccount()) && !"".equals(returnMoney.getPaymentAccount())){
            contract.setPaymentAccount(returnMoney.getPaymentAccount());
        }
        if ("2".equals(order.getOrderStatus())){
            contract.setContractStatus("2");
            contract.setPaymentStatus("1");
        }else if ("4".equals(order.getOrderStatus())){
            contract.setContractStatus("1");
            contract.setPaymentStatus("3");
        }else if ("5".equals(order.getOrderStatus())){
            contract.setContractStatus("1");
            contract.setPaymentStatus("4");
        }
        //到款日期
        contract.setPaymentDate(new Date());
        contract.setUpdatePeopleId(user.getAccountId());
        contract.setUpdateTm(new Date());
        //更新合同
        contractDbService.updateCustomerContract(contract);
        return contract;
    }

    /**
     * 维护客户表字段
     * @param contract 合同信息
     */
    @Override
    public void updateCustomer(CustomerContract contract){
        CustomerContractVO customerContractVO = contractDbService.getCustomerVipDateByCustomerId(contract.getCustomerId());
        Customer customer = customerDbService.selectCustomerById(contract.getCustomerId());
        if (Objects.nonNull(customer) && Objects.nonNull(customerContractVO)){
            if (customerContractVO.getVipProductMembershipLevel() >= customerContractVO.getProductMembershipLevel()){
                customer.setMembershipLevel(customerContractVO.getVipProductMembershipLevel());
            }else if (customerContractVO.getVipProductMembershipLevel() < customerContractVO.getProductMembershipLevel()){
                customer.setMembershipLevel(customerContractVO.getProductMembershipLevel());
            }
            boolean bo =true;
            //大于客户当前时间3个月视为新增客户
            if (Objects.nonNull(customer.getMembershipExpirationTm())){
                String vipEndDate =customer.getMembershipExpirationTm().toString();
                DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate endDate=customer.getMembershipExpirationTm().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                endDate = endDate.plusYears(3);
                Integer newVipEndDate =Integer.valueOf(endDate.toString().replaceAll("-",""));
                if (newVipEndDate >= Integer.valueOf(LocalDate.now().toString().replaceAll("-",""))){
                    customer.setNewOrderRenewalCustomer(1);
                    bo = false;
                }
            }
            if (bo){
                customer.setNewOrderRenewalCustomer(0);
            }
            customer.setMembershipStartTm(customerContractVO.getContractStartDate());
            customer.setMembershipExpirationTm(customerContractVO.getContractEndDate());
            customerDbService.updateCustomerByPrimaryKey(customer);
            //会员信息同步es
            customerService.syncESCustomerMembershipLevel(customer);
        }
    }


    @Override
    public boolean testReturnMoneyAndProduct(String orderNumber) {
        CustomerProductOrderVO order = productOrderDbService.selectOrderByNumber(orderNumber);
        String orderId = order.getProductOrderId();
        CustomerContract contract = contractDbService.selectContractByOrderId(orderId);
        Integer productCount = customerProductOrderDetailDbService.selectOrderProductCount(orderId);
        Integer finishProductCount = finishOrderDBservice.selectFinishProductCountByOrderId(orderId);
        if (productCount == finishProductCount) {  //产品数量相同
            BigDecimal big = returnMoneyDbservice.selectReturnMoneyCountByOrderId(orderId);
            if ("2".equals(order.getOrderStatus())) {  //完成的订单
                if (big.compareTo(contract.getContractReceivables()) == 0) {
                    return false;
                }
            }
            if ("4".equals(order.getOrderStatus())) {   //部分回款订单
                if (order.getPaidBackAmount().compareTo(big) == 0) {
                    return false;
                }
            }
            System.out.println("订单id: " + orderId + " 回款金额不相同");
            return true;
        }
        System.out.println("订单id: " + orderId + " 产品数量不相同");
        return true;
    }

    /**
     * 判断回款金额是否合法
     * @param returnMoney
     * @return
     */
    @Override
    public boolean ifReturnMoney(ReturnMoney returnMoney) {
        //获取订单信息
        CustomerProductOrderVO order=productOrderDbService.getOrderInfoById(returnMoney.getOrderId());
        CustomerContract customerContract = contractDbService.selectContractById(order.getContractId());
        BigDecimal big=new BigDecimal(0);
        if (Objects.nonNull(order) && Objects.isNull(order.getPaidBackAmount())){
            big=returnMoney.getArriveMoney();
        }else {
            big=order.getPaidBackAmount().add(returnMoney.getArriveMoney());
        }
        if (big.toString().indexOf(".") == -1){
            BigDecimal newMoney=new BigDecimal(big.toString()+".00");
            big = newMoney;
        }
        //新增回款，并且+起来的总额度大于订单总金额返回false
        if (Objects.isNull(returnMoney.getReturnMoneyId()) && (big.compareTo(customerContract.getContractReceivables()) > 0)){
            return false;
        }else if (Objects.nonNull(returnMoney.getReturnMoneyId())){
            //根据id查询回款信息
            ReturnMoneyVO returnMoneyVO =returnMoneyDbservice.getReturnMoenyInfoById(returnMoney.getReturnMoneyId());
            if (returnMoney.getArriveMoney().toString().indexOf(".") == -1){
                BigDecimal newMoney=new BigDecimal(returnMoney.getArriveMoney().toString()+".00");
                returnMoney.setArriveMoney(newMoney);
            }
            if (!returnMoneyVO.getArriveMoney().equals(returnMoney.getArriveMoney())){
                if (returnMoney.getArriveMoney().compareTo(returnMoneyVO.getArriveMoney()) > -1){ //现在的金额比原来的大
                    //新的金额
                    BigDecimal newMoney =returnMoney.getArriveMoney().subtract(returnMoneyVO.getArriveMoney()).add(order.getPaidBackAmount());
                    //新的回款总金额是否大于订单总金额
                    return newMoney.compareTo(customerContract.getContractReceivables()) <= -1 || newMoney.toString().equals(customerContract.getContractReceivables().toString());
                }
            }
        }
        return true;
    }

    /**
     * 判断合同状态是否正常
     * @param returnMoney
     * @return
     */
    @Override
    public boolean contractReviewStatus(ReturnMoney returnMoney) {
        //获取订单信息
        CustomerProductOrderVO order=productOrderDbService.getOrderInfoById(returnMoney.getOrderId());
        //获取合同信息
        CustomerContract contract = contractDbService.selectContractById(order.getContractId());
        //会员合同或特批 是否审批通过
        if (("2".equals(contract.getContractType())||"4".equals(contract.getContractType())) || "1".equals(contract.getSpecialApprovalStatus())){
            return "2".equals(contract.getContractReviewStatus());
        }
        return true;
    }

    /**
     * 同步chs_finish_order_product
     * @param finishList
     * @param index
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Override
    public AddFinishResultVO addFinishProductList(List<FinishOrderProduct> finishList,Integer index,String contractType,ReturnMoney returnMoney,Integer type){
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        CustomerProductOrder order = productOrderDbService.selectCustomerProductOrderById(finishList.get(0).getProductOrderId());
        CustomerContract contract = contractDbService.selectContractById(order.getContractId());
        Customer customer = customerDbService.selectCustomerById(order.getCustomerId());
        Integer count = 0;
        BigDecimal gradeMoney = new BigDecimal("0");
        for (int i=0;i<finishList.size();i++){
            for (int k=0;k<finishList.get(i).getProductQuantity();k++){
                FinishOrderProduct finishOrderProduct = finishList.get(i);
                finishOrderProduct.setContractType(contractType);
                finishOrderProduct.setFinishOrderProductId(CommonUtils.getGUID());
                finishOrderProduct.setFinishOrderProductNum(String.valueOf(new Date().getTime())+i+k);
                finishOrderProduct.setCreatePeopleId(userAccount.getAccountId());
                finishOrderProduct.setCreateTm(new Date());
                finishOrderProduct.setSalesmanId(order.getCreatePeopleId());
                finishOrderProduct.setCompanyId(order.getAffiliationCompanyId());
                finishOrderProduct.setArriveTime(returnMoney.getArriveTime());
                finishOrderProduct.setOrderNumber(order.getOrderNumber());
                finishOrderProduct.setContractNumber(contract.getContractNumber());
                finishOrderProduct.setCustomerName(customer.getCustomerName());
                finishOrderProduct.setSource(type);
                if (!"3".equals(finishOrderProduct.getOrderDetailType())){
                    BigDecimal ratio = customerMemberProductDbService.selectProductPerformanceRatio(finishOrderProduct.getProductCategories(),finishOrderProduct.getProductId());
                    finishOrderProduct.setPerformanceConversionRatio(ratio);
                    OrderActivityVO activityVO = customerProductOrderDetailDbService.selectActivityProductCount(finishList.get(i).getProductOrderDetailId());
                    if (Objects.nonNull(activityVO)){
                        boolean b = true;
                        if (Objects.isNull(ratio)){
                            b =false;
                        }
                        if ( b && "2".equals(finishList.get(i).getOrderDetailType()) && Integer.valueOf(activityVO.getProductCount()) > 0){
                            finishOrderProduct.setGradeMoney(activityVO.getActivityFinalPrice().divide(new BigDecimal(activityVO.getProductCount()),2).multiply(ratio));
                        }
                        if (b && "1".equals(finishList.get(i).getOrderDetailType())){
                            finishOrderProduct.setGradeMoney(finishOrderProduct.getProductFinalPrice().multiply(ratio));
                        }
                        if ("1".equals(contract.getWhetherCooperateDevelopment())){
                            BigDecimal finalPrice = finishOrderProduct.getProductFinalPrice();
                            BigDecimal gradeMoney2 = finishOrderProduct.getGradeMoney();
                            List<CustomerContractDeveloper> developerList = customerContractDeveloperDbService.selectCustomerContractDeveloperList(contract.getContractId());
                            //订单实际总金额
                            BigDecimal orderActualTotalAmount = order.getOrderActualTotalAmount();
                            for (int d=0;d<developerList.size();d++){
                                if ( b && "2".equals(finishList.get(i).getOrderDetailType()) && Integer.valueOf(activityVO.getProductCount()) > 0){
                                    finishOrderProduct.setGradeMoney(activityVO.getActivityFinalPrice().divide(new BigDecimal(activityVO.getProductCount()),2).multiply(ratio));
                                }
                                if (b && "1".equals(finishList.get(i).getOrderDetailType())){
                                    finishOrderProduct.setGradeMoney(finishOrderProduct.getProductFinalPrice().multiply(ratio));
                                }
                                finishOrderProduct.setFinishOrderProductId(CommonUtils.getGUID());
                                UserAccount developerUser = userAccountDbService.selectUserAccountByUserId(developerList.get(d).getCoDeveloper());
                                finishOrderProduct.setSalesmanId(developerUser.getAccountId());
                                finishOrderProduct.setCompanyId(developerUser.getCompanyId());
                                //判断合作开发主从
                                if (developerUser.getAccountId().equals(order.getCreatePeopleId())){
                                    finishOrderProduct.setCooperateType("1");
                                }else {
                                    finishOrderProduct.setCooperateType("2");
                                }
                                //比例
                                BigDecimal partRatio = developerList.get(d).getAllocationMount().divide(orderActualTotalAmount,5,BigDecimal.ROUND_DOWN);
                                //拆分业绩金额
                                if (Objects.nonNull(gradeMoney2)
                                        && !new BigDecimal("0") .equals(gradeMoney2) && !new BigDecimal("0.00") .equals(gradeMoney2)){
                                    finishOrderProduct.setPartGradeMoney(gradeMoney2);
                                    finishOrderProduct.setGradeMoney(gradeMoney2.multiply(partRatio));
                                }
                                //拆分产品成交价
                                if (Objects.nonNull(finalPrice)
                                        && !new BigDecimal("0") .equals(finalPrice) && !new BigDecimal("0.00") .equals(finalPrice)){
                                    finishOrderProduct.setProductPartFinalPrice(finalPrice);
                                    finishOrderProduct.setProductFinalPrice(finalPrice.multiply(partRatio));
                                }
                                if (Objects.isNull(finishOrderProduct.getGradeMoney())){
                                    finishOrderProduct.setGradeMoney(new BigDecimal("0"));
                                }
                                Integer num = finishOrderDBservice.insertFinishProduct(finishOrderProduct);
                                count += num;
                                gradeMoney = gradeMoney.add(finishOrderProduct.getGradeMoney());
                            }
                            AddFinishResultVO resultVO = new AddFinishResultVO();
                            resultVO.setCount(count);
                            resultVO.setGradeMoney(gradeMoney);
                            return resultVO;
                        }
                    }
                }
                if ("0".equals(contract.getWhetherCooperateDevelopment())){
                    if (Objects.isNull(finishOrderProduct.getGradeMoney())){
                        finishOrderProduct.setGradeMoney(new BigDecimal("0"));
                    }
                    Integer num = finishOrderDBservice.insertFinishProduct(finishOrderProduct);
                    count += num;
                    gradeMoney = gradeMoney.add(finishOrderProduct.getGradeMoney());
                }
            }
        }
        AddFinishResultVO resultVO = new AddFinishResultVO();
        resultVO.setCount(count);
        resultVO.setGradeMoney(gradeMoney);
        return resultVO;
    }

    /**
     * 业绩、到款金额存redis
     * @param gradeMoney 业绩金额
     * @param companyId 公司id
     * @param returnMoney 到款金额
     * @param arriveTime 到款时间
     */
    @Override
    public void returnMoneyToRedis(BigDecimal gradeMoney,String companyId,BigDecimal returnMoney,Date arriveTime){
        returnMoneyRedisService.returnMoneyToRedis(companyId,gradeMoney,returnMoney,arriveTime);
    }

    /**
     * 订单是否作废
     * @param returnMoney
     * @return
     */
    @Override
    public boolean orderIfAbolish(ReturnMoney returnMoney) {
        //获取订单信息
        CustomerProductOrderVO order=productOrderDbService.getOrderInfoById(returnMoney.getOrderId());
        if (Objects.nonNull(order)){
            return !"3".equals(order.getOrderStatus());
        }
        return true;
    }

    /**
     * 删除回款信息
     * @param returnMoneyId
     */
    @Override
    public boolean delReturnMoney(String returnMoneyId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        //根据id查询回款信息
        ReturnMoneyVO returnMoneyVO = returnMoneyDbservice.getReturnMoenyInfoById(returnMoneyId);
        Date arriveTime = returnMoneyDbservice.selectOrderMaxArriveTime(returnMoneyVO.getOrderId());
        Integer updateNumber = returnMoneyDbservice.delReturnMoney(returnMoneyId,userAccount.getAccountId());
        if (updateNumber < 1){
            return false;
        }
        UserAccount user = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        //订单信息
        CustomerProductOrder order=productOrderDbService.selectCustomerProductOrderById(returnMoneyVO.getOrderId());
        String orderStatus = order.getOrderStatus();
        BigDecimal gradeMoney = finishOrderDBservice.selectGradeMoneyByOrderId(order.getProductOrderId());
        FinishOrderProduct finish = finishOrderDBservice.selectFinishOrderProductById(returnMoneyVO.getFinishOrderProductId());
        if (Objects.nonNull(finish)){
            if (returnMoneyVO.getArriveMoney().compareTo(finish.getProductFinalPrice()) == 0){
                finish.setProductStatus("0");
            }else {
                finish.setProductStatus("2");
            }
            if (Objects.nonNull(returnMoneyVO.getArriveMoney()) && new BigDecimal("0").compareTo(returnMoneyVO.getArriveMoney()) != 1){
                finish.setGradeMoney(finish.getGradeMoney().subtract(returnMoneyVO.getArriveMoney().divide(finish.getPerformanceConversionRatio())));
            }
            finishOrderDBservice.updateFinishOrderProduct(finish);
        }
        //清空chs_finish_order_product表
        if ("2".equals(order.getOrderStatus())){
            List<FinishOrderProduct> list = finishOrderDBservice.selectFinishOrderProductList(null,order.getProductOrderId());
            //退码
            for (int i=0;i<list.size();i++){
                CustomerOrderBackMoney customerOrderBackMoney = new CustomerOrderBackMoney();
                customerOrderBackMoney.setFinishOrderProductNum(list.get(i).getFinishOrderProductNum());
                customerProductOrderService.backProduct(order.getProductOrderId(),customerOrderBackMoney.getFinishOrderProductNum());
            }
        }
        //合同信息
        CustomerContract contract=contractDbService.selectContractById(order.getContractId());
        String residueMoney= order.getPaidBackAmount().subtract(returnMoneyVO.getArriveMoney()).toString();
        if (residueMoney.indexOf("-") != -1){
            residueMoney = "0.00";
        }
        order.setPaidBackAmount(new BigDecimal(residueMoney));
        order.setUpdatePeopleId(user.getAccountId());
        order.setUpdateTm(new Date());
        order.setOrderCompleteTm(null);
        //合同未生效
        contract.setContractStatus("1");
        //订单回退到等待回款状态
        if ("0.00".equals(residueMoney)){
            order.setOrderStatus("1");
            //更新合同
            contract.setPaymentStatus("0");
            contract.setContractTotalPaymentAmount(order.getPaidBackAmount());
            contract.setPaymentNumber(contract.getPaymentNumber() - 1);
        }else{
            order.setOrderStatus("4");
            //更新合同
            contract.setPaymentStatus("3");
            contract.setContractTotalPaymentAmount(order.getPaidBackAmount());
            contract.setPaymentNumber(contract.getPaymentNumber() - 1);
        }
        //查询合同最后一次回款记录
        ReturnMoneyVO finallyReturnMoneyVO = returnMoneyDbservice.selectFinallyReturnMoneyByOrderId(order.getProductOrderId());
        if (Objects.nonNull(finallyReturnMoneyVO)){
            if (Objects.nonNull(finallyReturnMoneyVO.getUpdateTm())){
                contract.setPaymentDate(finallyReturnMoneyVO.getUpdateTm());
            }else {
                contract.setPaymentDate(finallyReturnMoneyVO.getCreateTm());
            }
        }else {
            contract.setPaymentDate(null);
        }
        productOrderDbService.updateByPrimaryKey(order);
        contractDbService.updateByPrimaryKey(contract);

        ReturnMoneyLog returnMoneyLog=new ReturnMoneyLog();
        returnMoneyLog.setCreatePeopleId(user.getAccountId());
        returnMoneyLog.setCreateTm(new Date());
        returnMoneyLog.setReturnMoneyId(returnMoneyId);
        returnMoneyLog.setReturnMoneyLogId(CommonUtils.getGUID());
        returnMoneyLog.setOperatorType(2);
        //回款修改记录
        returnMoneyLogDbService.addReturnMoneyLog(returnMoneyLog);
        if ("2".equals(orderStatus)){
            returnMoneyRedisService.delReturnMoney(arriveTime,returnMoneyVO.getFilialeId(),new BigDecimal("0"),gradeMoney);
            returnMoneyRedisService.delReturnMoney(returnMoneyVO.getArriveTime(),returnMoneyVO.getFilialeId(),returnMoneyVO.getArriveMoney(),new BigDecimal("0"));
        }
        return true;
    }

    /**
     * 导入到款记录
     * @param list
     * @param companyId
     * @return
     */
    @Override
    public JSONObject importReturnMoney(List<ImportReturnMoneyVO> list, String companyId) {
        UserAccount loginUserAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        //返回的结果集
        JSONObject jsonObject = new JSONObject();
        //导入数量
        int importNum = 0;
        //重复的行数
        String repeatIdStr = "";
        //失败行数
        String importFailIdStr = "";

        if (list.size() > 0){
            int count = 100;                   //一个线程处理300条数据
            int listSize = list.size();        //数据集合大小
            int runSize = (listSize/count)+1;  //开启的线程数
            //int runSize = importExportService.calculateImportedThreads(listSize);

            List<ImportReturnMoneyVO> newlist = null;       //存放每个线程的执行数据

            ExecutorService executor = Executors.newCachedThreadPool();
            //创建两个个计数器
            CountDownLatch begin = new CountDownLatch(1);
            CountDownLatch end = new CountDownLatch(runSize);
            List<FutureTask<JSONObject>> taskList = new ArrayList<FutureTask<JSONObject>>();
            for (int i = 0; i < runSize ; i++) {
                //计算每个线程执行的数据
                if ((i + 1) == runSize) {
                    int startIndex = (i * count);
                    int endIndex = list.size();
                    newlist = list.subList(startIndex, endIndex);
                } else {
                    int startIndex = (i * count);
                    int endIndex = (i + 1) * count;
                    if (endIndex > list.size()){
                        endIndex = list.size();
                    }
                    newlist = list.subList(startIndex, endIndex);
                }
                FutureTask<JSONObject> futureTask = new FutureTask(new InsertReturnMoneyCallable(returnMoneyDbservice,newlist, begin, end,companyId,userAccountDbService,importFailureLogDbService,customerDbService,productOrderDbService,companyDbService,contractDbService,sendRoyaltyDbService));
                taskList.add(futureTask);
                executor.submit(futureTask);//submit返回一个Future，代表了即将要返回的结果
            }
            //重复的行数
            List<Integer> repeatIdList = new ArrayList();
            //失败行数
            List<Integer> importFailIdList = new ArrayList();

            for (int i = 0; i < taskList.size(); i++) {
                try {
                    // FutureTask的get方法会自动阻塞,直到获取计算结果为止
                    //导入数量
                    importNum = importNum + taskList.get(i).get().getInteger("importNum");

                    //重复数量
                    JSONArray repeatIdArray = taskList.get(i).get().getJSONArray("repeatIdStr");
                    for (int j = 0; j < repeatIdArray.size(); j++){
                        int repeat = Integer.parseInt(repeatIdArray.get(j).toString());
                        repeatIdList.add(repeat + i*100);
                    }

                    //失败数量
                    JSONArray importFailIdArray = taskList.get(i).get().getJSONArray("importFailIdStr");
                    for (int j = 0; j < importFailIdArray.size(); j++){
                        int importFail = Integer.parseInt(importFailIdArray.get(j).toString());
                        importFailIdList.add(importFail + i*100);
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }

            // 关闭线程池
            executor.shutdown();

            jsonObject.put("importClueNum", importNum);
            jsonObject.put("repeatIdStr", repeatIdList);
            jsonObject.put("importFailIdStr", importFailIdList);

        }
        return jsonObject;
    }

    public String arriveMethod(Integer arriveMethod){
        String s= "";
        if (0 ==arriveMethod){
            s = "银行汇款";
        }
        if (1 ==arriveMethod){
            s = "现金";
        }
        if (2 ==arriveMethod){
            s = "余额支付";
        }
        if (3 ==arriveMethod){
            s = "线上支付";
        }
        if (4 ==arriveMethod){
            s = "转入额支付";
        }
        if (5 ==arriveMethod){
            s = "微信支付";
        }
        return s;
    }

    /**
     * 根据主键Id修改提成发放状态
     * @Author pym
     * @Date  2021/9/24 10:09
     * @param returnMoneyIds 回款记录表主键
     * @param royaltyStatus 提成发放状态 0 未发放 1已发放
     * @return {@link {java.lang.Boolean}}
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void updateRoyaltyStatusByReturnMoneyId(List<String> returnMoneyIds, String royaltyStatus) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        String accountId = userAccount.getAccountId();
        Date operateTime = new Date();
        int operateQuantity = returnMoneyIds.size();
        ModifyRoyaltyStatus modifyRoyaltyStatus = getModifyRoyaltyStatus(operateQuantity, accountId, operateTime);
        String modifyRoyaltyStatusId = modifyRoyaltyStatus.getModifyRoyaltyStatusId();
        String modifyRoyaltyModifyAfter = royaltyStatus;
        if ("0".equals(royaltyStatus)) {
            modifyRoyaltyModifyAfter = "未发放";
        }
        if ("1".equals(royaltyStatus)) {
            modifyRoyaltyModifyAfter = "已发放";
        }
        List<InsertModifyRoyaltyStatusLogVO> insertModifyRoyaltyStatusLogVOList = modifyRoyaltyStatusLogDbService
                .selectInsertModifyRoyaltyStatusLogVOList(returnMoneyIds, modifyRoyaltyStatusId, operateTime, modifyRoyaltyModifyAfter, accountId);
        returnMoneyDbservice.updateRoyaltyStatusByReturnMoneyId(returnMoneyIds, Integer.parseInt(royaltyStatus), accountId, operateTime);
        modifyRoyaltyStatusLogDbService.batchInsertModifyRoyaltyStatusLog(insertModifyRoyaltyStatusLogVOList);
        modifyRoyaltyStatusDbService.insertModifyRoyaltyStatus(modifyRoyaltyStatus);
    }

    /**
     * 获取修改回款提成发放状态记录
     * @Author pym
     * @Date  2021/11/25 14:56
     * @param operateQuantity 操作数量
     * @param accountId 账号Id
     * @param operateTime 操作时间
     * @return {@link {com.crm.model.entity.returnMoney.ModifyRoyaltyStatus}}
     */
    private ModifyRoyaltyStatus getModifyRoyaltyStatus(int operateQuantity, String accountId, Date operateTime) {
        ModifyRoyaltyStatus modifyRoyaltyStatus = new ModifyRoyaltyStatus();
        modifyRoyaltyStatus.setModifyRoyaltyStatusId(CommonUtils.getGUID());
        modifyRoyaltyStatus.setOperatePeopleId(accountId);
        modifyRoyaltyStatus.setOperateTime(operateTime);
        modifyRoyaltyStatus.setOperateQuantity(operateQuantity);
        return modifyRoyaltyStatus;
    }

    /**
     * (补充回款表、合同表、订单表、订单完成表:客户信息-customer_id、customer_name以及订单完成表)--正式库临时用来补充已有的数据没有客户信息的
     * @param companyId --公司ID
     * @param list      --导入的回款数据(订单编号、所属客户)
     * @author yincuimei
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Override
    public String addReturnMoneyCustomerInfo(String companyId,List<ImportOrderNumber> list) {
        String resultMessage = "";
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        String accountId = userAccount.getAccountId();//当前操作人ID
        //要补充客户的回款表List
        List<ReturnMoney> returnMoneyUpdateList = new ArrayList<ReturnMoney>();
        //要补充客户的合同表List
        List<CustomerContract> customerContractUpdateList = new ArrayList<CustomerContract>();
        //要补充客户的订单表List
        List<CustomerProductOrder> customerProductOrderUpdateList = new ArrayList<CustomerProductOrder>();
        //要补充的订单完成表List
        List<FinishOrderProduct> finishOrderProductList = new ArrayList<FinishOrderProduct>();

        if(!StringUtils.isBlank(companyId) && list != null && list.size() > 0){
            //1. 查询数据库中回款表客户信息为空的数据
            List<ReturnMoney> returnMoneyList = returnMoneyDbservice.selectReturnMoneyNoCustomer(companyId);
            if(returnMoneyList != null &&  returnMoneyList.size() > 0) {
                //数据库中客户为空的map数据(key为订单编号;value是为空数据的对象)
                Map<String, ReturnMoney> returnMoneyMap = returnMoneyList.stream().collect(
                        Collectors.toMap(ReturnMoney::getOrderNumber, Function.identity(), (key1, key2) -> key2));
                //导入的map数据(key为订单编号;value为所属客户)
                Map<String, String> importDataMap = list.stream().collect(
                        Collectors.toMap(ImportOrderNumber::getOrderNumber,
                                p -> p.getCustomerName() == null ? "" : p.getCustomerName(), (key1, key2) -> key2));
                //2.和导入的数据对比订单号
                for (Map.Entry<String, ReturnMoney> entry : returnMoneyMap.entrySet()) {
                    if (importDataMap.containsKey(entry.getKey())) {
                        String customerName = importDataMap.get(entry.getKey());//取出当前订单客户名
                        String customerId = "";//客户ID
                        ReturnMoney returnMoney = entry.getValue();
                        if (!StringUtils.isBlank(customerName)) {
                            returnMoney.setCustomerName(customerName);
                            //3.根据导入数据的所属客户查询customerId(查chs_customer表)
                            customerId = customerDbService.selectCustomerIdByName(customerName);
                            if (!StringUtils.isBlank(customerId)) {
                                returnMoney.setCustomerId(customerId);
                            }
                            returnMoney.setUpdateTm(new Date());//更新时间
                            returnMoney.setUpdateBy(accountId);//更新人
                            returnMoney.setMaintainStatus(2);//维护状态
                            returnMoneyUpdateList.add(returnMoney);

                            if (!StringUtils.isBlank(returnMoney.getContractId())) {
                                CustomerContract customerContract = new CustomerContract();
                                customerContract.setContractId(returnMoney.getContractId());//合同ID
                                customerContract.setCustomerId(customerId);//客户ID
                                customerContract.setCustomerName(customerName);
                                customerContract.setUpdateTm(new Date());//更新时间
                                customerContract.setUpdatePeopleId(accountId);//更新人
                                customerContract.setMaintainStatus(2);//维护状态
                                customerContractUpdateList.add(customerContract);
                            }

                            if (!StringUtils.isBlank(returnMoney.getOrderId())) {
                                CustomerProductOrder customerProductOrder = new CustomerProductOrder();
                                customerProductOrder.setProductOrderId(returnMoney.getOrderId());
                                customerProductOrder.setCustomerId(customerId);
                                customerProductOrder.setCustomerName(customerName);
                                customerProductOrder.setUpdateTm(new Date());//更新时间
                                customerProductOrder.setUpdatePeopleId(accountId);//更新人
                                customerProductOrder.setMaintainStatus(2);//维护状态
                                customerProductOrderUpdateList.add(customerProductOrder);

                                FinishOrderProduct finishOrderProduct = new FinishOrderProduct();
                                finishOrderProduct.setProductOrderId(returnMoney.getOrderId());
                                finishOrderProduct.setCustomerName(customerName);//客户名称
                                finishOrderProduct.setUpdateTm(new Date());//更新时间
                                finishOrderProduct.setUpdatePeopleId(accountId);//更新人ID
                                finishOrderProduct.setMaintainStatus(2);//维护状态
                                finishOrderProductList.add(finishOrderProduct);
                            }
                        }
                    }
                }
            }
        }
        //批量更新回款表(customer_id、customer_name数据)
        if(returnMoneyUpdateList != null && returnMoneyUpdateList.size() > 0){
            Boolean resultFlag = returnMoneyDbservice.batchUpdateReturnMoneyByOrderNumber(returnMoneyUpdateList);
            if(resultFlag){
                resultMessage += "回款表更新成功 : " + returnMoneyUpdateList.size() + "条数据" + "</br>";
            }
        }
        //批量更新合同表(customer_id、customer_name数据)
        if(customerContractUpdateList != null && customerContractUpdateList.size() > 0){
            Boolean resultFlag = customerContractDbService.batchUpdateCustomerContractByIds(customerContractUpdateList);
            if(resultFlag){
                resultMessage += "合同表更新成功 : " + customerContractUpdateList.size() + "条数据"  + "</br>";
            }
        }
        //批量更新订单表(customer_id、customer_name数据)
        if(customerProductOrderUpdateList != null && customerProductOrderUpdateList.size() > 0){
            Boolean resultFlag = customerProductOrderDbService.batchUpdateCustomerProductOrderByIds(customerProductOrderUpdateList);
            if(resultFlag){
                resultMessage += "订单表更新成功 : " + customerProductOrderUpdateList.size() + "条数据"  + "</br>";
            }
        }
        //批量更新订单完成表(customer_name数据)
        if(finishOrderProductList != null && finishOrderProductList.size() > 0){
            Boolean resultFlag = finishOrderProductDbService.batchUpdateFinishOrderProductByOrderId(finishOrderProductList);
            if(resultFlag){
                resultMessage += "订单完成表更新成功 : " + finishOrderProductList.size() + "条数据";
            }
        }
        return resultMessage;
    }

    /**
     * 财务明细
     * @return
     */
    @Override
    public DhPageInfo<FinancialDetailsVO> selectFinancialDetails(ReturnMoneyQO returnMoneyQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息

        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //4是分公司财务 3是总部财务
        if ("4".equals(userAccount.getDeptId())){
            returnMoneyQO.setBs(1);
            returnMoneyQO.setCompanyId(userAccount.getCompanyId());
        }

        List<FinancialDetailsVO> returnMoneyVOList= returnMoneyDbservice.selectFinancialDetails(returnMoneyQO);
        PageInfo<FinancialDetailsVO> pageInfo = new PageInfo<FinancialDetailsVO>(returnMoneyVOList);
        return new DhPageInfo<FinancialDetailsVO>(pageInfo, returnMoneyVOList);
    }

    /**
     * 业绩明细
     * @return
     */
    @Override
    public DhPageInfo<PerformanceDetailsVO> selectPerformanceDetails(ReturnMoneyQO returnMoneyQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        if(returnMoneyQO.getDateUnit() != null) {
            if(2 == returnMoneyQO.getDateUnit()) {
                returnMoneyQO.setMonth(returnMoneyQO.getYear() + returnMoneyQO.getMonth());
            }
        }


        List<PerformanceDetailsVO> returnMoneyVOList= returnMoneyDbservice.selectPerformanceDetails(returnMoneyQO);
        PageInfo<PerformanceDetailsVO> pageInfo = new PageInfo<PerformanceDetailsVO>(returnMoneyVOList);
        return new DhPageInfo<PerformanceDetailsVO>(pageInfo, returnMoneyVOList);
    }

    /**
     * 业绩明细
     * @return
     */
    @Override
    public List<PerformanceDetailsVO> selectMonthPerformanceDetails(ReturnMoneyQO returnMoneyQO) {
        if(returnMoneyQO.getDateUnit() != null) {
            if(2 == returnMoneyQO.getDateUnit()) {
                returnMoneyQO.setMonth(returnMoneyQO.getYear() + returnMoneyQO.getMonth());
            }
        }

        List<PerformanceDetailsVO> returnMoneyVOList= returnMoneyDbservice.selectPerformanceDetails(returnMoneyQO);
        return returnMoneyVOList;
    }

    /**
     * 导出业绩明细数据
     * @param returnMoneyQO
     * @return
     */
    @Override
    public List<PerformanceDetailsVO> exportPerformanceDetails(ReturnMoneyQO returnMoneyQO) {
        if(returnMoneyQO.getDateUnit() != null) {
            if(2 == returnMoneyQO.getDateUnit()) {
                returnMoneyQO.setMonth(returnMoneyQO.getYear() + returnMoneyQO.getMonth());
            }
        }
        List<PerformanceDetailsVO> list= returnMoneyDbservice.selectPerformanceDetails(returnMoneyQO);
        return list;
    }

    /**
     * 查询公司列表
     * @return
     */
    @Override
    public List<SysCompany> selectSysCompanyList() {
        return companyDbService.selectSysCompanyList();
    }

    /*@Override
    public Boolean updateDate() {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("startTm", "2021-09-10");
        paramMap.put("endTm", "2021-09-29");
        paramMap.put("memberCardNumber", "3100042");
        log.info("请求数据---"+paramMap);
        String res= HttpUtil.post("http://47.105.120.170:8081/loginFree/updateDate", paramMap);
        log.info("返回数据---"+res);
        JSONObject json = JSON.parseObject(res);
        return true;
    }*/

    /**
     * 统计个人业绩总和
     * @return
     */
    @Override
    public BigDecimal sumScoreMoney(ReturnMoneyQO returnMoneyQO) {

        if(2 == returnMoneyQO.getDateUnit()) {
            returnMoneyQO.setMonth(returnMoneyQO.getYear() + returnMoneyQO.getMonth());
        }
        BigDecimal score = new BigDecimal("0");
        BigDecimal customerScore = returnMoneyDbservice.sumCustomerPay(returnMoneyQO);
        BigDecimal returnScore = returnMoneyDbservice.sumReturnScoreMoney(returnMoneyQO);
        if(customerScore != null) {
            score = customerScore;
        }
        if(returnScore != null) {
            score = returnScore;
        }
        if(customerScore != null && returnScore != null) {
            score = customerScore.add(returnScore);
        }

        return score;
    }

    /**
     * 报表统计 - 业绩分析 - 销售产品分析
     * @Author pym
     * @Date  2021/9/27 14:48
     * @param pageIndex -页码
     * @param pageSize -分页大小
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     * @param analyseReturnMoneyProductQO -查询条件
     * @return {@link {com.crm.common.model.DhPageInfo<com.crm.model.vo.productManager.AnalyseReturnMoneyProductVO>}}
     */
    @Override
    public DhPageInfo<AnalyseReturnMoneyProductVO> selectReturnMoneyProductList(Integer pageIndex, Integer pageSize,
                                                                                String sortName, String sortOrder,
                                                                                AnalyseReturnMoneyProductQO analyseReturnMoneyProductQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //排序字符串拼接
        String order = getOrder(sortName, sortOrder);
        List<AnalyseReturnMoneyProductVO> returnMoneyProductList = returnMoneyDbservice.selectReturnMoneyProductList(analyseReturnMoneyProductQO,order,userAccount.getAccountId());
        PageInfo<AnalyseReturnMoneyProductVO> pageInfo = new PageInfo<AnalyseReturnMoneyProductVO>(returnMoneyProductList);
        return new DhPageInfo<AnalyseReturnMoneyProductVO>(pageInfo, returnMoneyProductList);
    }



    /**
     * 排序字符串拼接
     * @Author pym
     * @Date  2021/8/19 10:45
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     * @return {@link {java.lang.String}}
     */
    private String getOrder(String sortName, String sortOrder) {
        String order = "";
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch(sortName){
                case "productName":
                { //产品名称
                    order = getOrder(order, sortOrder, "product_name");
                }
                break;
                case "arriveMoney":
                { //到款金额
                    order = getOrder(order, sortOrder, "arrive_money");
                }
                break;
                case "orderNumber":
                { //订单编号
                    order = getOrder(order, sortOrder, "order_number");
                }
                break;
                case "contractNumber":
                { //合同编号
                    order = getOrder(order, sortOrder, "contract_number");
                }
                break;
                case "productCategories":
                { //产品类型
                    order = getOrder(order, sortOrder, "product_categories");
                }
                break;
                case "royaltyStatus":
                { //提成发放状态
                    order = getOrder(order, sortOrder, "royalty_status");
                }
                break;
                case "scoreConvertRatio":
                { //业绩换算比例
                    order = getOrder(order, sortOrder, "score_convert_ratio");
                }
                break;
                case "performanceConversionRatio":
                { //业绩换算比例
                    order = getOrder(order, sortOrder, "performance_conversion_ratio");
                }
                break;
                case "scoreMoney":
                { //业绩金额
                    order = getOrder(order, sortOrder, "score_money");
                }
                break;
                case "royaltyMoney":
                { //提成金额
                    order = getOrder(order, sortOrder, "royalty_money");
                }
                break;
                case "createBy":
                { //录入人
                    order = getOrder(order, sortOrder, "create_by");
                }
                break;
                case "arriveTime":
                { //到款时间
                    order = getOrder(order, sortOrder, "arrive_time");
                }
                break;
                case "salesman":
                { //所属业务员
                    order = getOrder(order, sortOrder, "salesman_id");
                }
                break;
                default:
                    break;
            }
        }
        if (!order.contains("score_money")) {
            order = getOrder(order, "DESC", "score_money");
        }
        return order;
    }

    /**
     * 排序字符串拼接
     * @Author pym
     * @Date  2021/8/19 10:45
     * @param order -排序字符串
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     * @return {@link {java.lang.String}}
     */
    private String getOrder(String order, String sortOrder, String sortName) {
        if (StringUtils.isBlank(order)) {
            order += sortName +" "+ sortOrder;
        } else {
            order += ","+sortName +" " + sortOrder;
        }
        return order;
    }

    /**
     * 报表统计 - 业绩分析 - 销售额度统计表
     * @Author pym
     * @Date  2021/10/21 10:01
     * @param analyseReturnMoneyProductQO  -查询条件
     * @return {@link {com.crm.model.vo.productManager.PerformanceAnalysisVO}}
     */
    @Override
    public PerformanceAnalysisVO selectPerformanceAnalysis(AnalyseReturnMoneyProductQO analyseReturnMoneyProductQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        String accountId = userAccount.getAccountId();
        Date year = analyseReturnMoneyProductQO.getYear();
        Date month = analyseReturnMoneyProductQO.getMonth();
        SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat sdf1= new SimpleDateFormat("yyyy");
        SimpleDateFormat sdf2 = new SimpleDateFormat("MM");
        PerformanceAnalysisVO performanceAnalysisVO = new PerformanceAnalysisVO();
        PerformanceAnalysisVO vo;
        List<PerformanceAnalysisVO> voList;
        BigDecimal totalMemberProductsPrice = new BigDecimal("0.00");
        Integer totalMemberProductsCount = 0;
        BigDecimal totalNonMemberProductsPrice = new BigDecimal("0.00");
        Integer totalNonMemberProductsCount = 0;
        try {
            if (Objects.nonNull(month)) {
                String monthFormat = sdf0.format(month);
                String monthStartDate = monthFormat + "-01";
                String monthEndDate = YearWeeksUtil.getMonthEnd( Integer.valueOf(sdf1.format(month)), Integer.valueOf(sdf2.format(month)));
                List<String> weeks = YearWeeksUtil.getWeeks(monthStartDate, monthEndDate);
                //每周的开始日期和结束日期
                performanceAnalysisVO.setDateList(weeks);
                for (int i = 0; i < weeks.size(); i++) {
                    String week = weeks.get(i);
                    String startDate = week.split(" 至 ")[0];
                    String endDate = week.split(" 至 ")[1];
                    //会员产品
                    vo = returnMoneyDbservice.selectMemberProductCountAndPrice(accountId, startDate, endDate);
                    if (Objects.nonNull(vo)) {
                        BigDecimal salesQuotaOfMemberProducts = vo.getSalesQuotaOfMemberProducts();
                        Integer numberOfMemberProducts = vo.getNumberOfMemberProducts();
                        performanceAnalysisVO.getMemberProductList().add(salesQuotaOfMemberProducts);
                        totalMemberProductsPrice = totalMemberProductsPrice.add(salesQuotaOfMemberProducts);
                        totalMemberProductsCount += numberOfMemberProducts;
                    }
                    //非会员产品
                    vo = returnMoneyDbservice.selectNonMemberProductCountAndPrice(accountId, startDate, endDate);
                    if (Objects.nonNull(vo)) {
                        BigDecimal salesQuotaOfNonMemberProducts = vo.getSalesQuotaOfNonMemberProducts();
                        Integer numberOfNonMemberProducts = vo.getNumberOfNonMemberProducts();
                        performanceAnalysisVO.getNonMemberProductList().add(salesQuotaOfNonMemberProducts);
                        totalNonMemberProductsPrice = totalNonMemberProductsPrice.add(salesQuotaOfNonMemberProducts);
                        totalNonMemberProductsCount += numberOfNonMemberProducts;
                    }
                }
            } else if (Objects.nonNull(year)) {
                //会员产品
                voList = returnMoneyDbservice.selectYearMemberProductCountAndPrice(accountId, year);
                if (Objects.nonNull(voList) && voList.size() > 0) {
                    for (int i = 0; i < voList.size(); i++) {
                        PerformanceAnalysisVO performanceAnalysis = voList.get(i);
                        BigDecimal salesQuotaOfMemberProducts = performanceAnalysis.getSalesQuotaOfMemberProducts();
                        Integer numberOfMemberProducts = performanceAnalysis.getNumberOfMemberProducts();
                        performanceAnalysisVO.getMemberProductList().add(salesQuotaOfMemberProducts);
                        totalMemberProductsPrice = totalMemberProductsPrice.add(salesQuotaOfMemberProducts);
                        totalMemberProductsCount += numberOfMemberProducts;
                    }
                }
                //非会员产品
                voList = returnMoneyDbservice.selectYearNonMemberProductCountAndPrice(accountId, year);
                if (Objects.nonNull(voList) && voList.size() > 0) {
                    for (int i = 0; i < voList.size(); i++) {
                        PerformanceAnalysisVO performanceAnalysis = voList.get(i);
                        BigDecimal salesQuotaOfNonMemberProducts = performanceAnalysis.getSalesQuotaOfNonMemberProducts();
                        Integer numberOfNonMemberProducts = performanceAnalysis.getNumberOfNonMemberProducts();
                        performanceAnalysisVO.getNonMemberProductList().add(salesQuotaOfNonMemberProducts);
                        totalNonMemberProductsPrice = totalNonMemberProductsPrice.add(salesQuotaOfNonMemberProducts);
                        totalNonMemberProductsCount += numberOfNonMemberProducts;
                    }
                }
            }
            performanceAnalysisVO.setSalesQuotaOfMemberProducts(totalMemberProductsPrice);
            performanceAnalysisVO.setNumberOfMemberProducts(totalMemberProductsCount);
            performanceAnalysisVO.setSalesQuotaOfNonMemberProducts(totalNonMemberProductsPrice);
            performanceAnalysisVO.setNumberOfNonMemberProducts(totalNonMemberProductsCount);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return performanceAnalysisVO;
    }

    /**
     * 双十一报表
     * @param entryArea
     * @param month
     * @return
     */
    @Override
    public List<PerformanceRankVO> reportForNovember(String entryArea,String year, String month, String day){
        return returnMoneyDbservice.reportForNovember(entryArea,year,month,day);
    }

    @Override
    public List<ReportPerformanceTop> getReportPerformanceTop() {
        return reportPerformanceTopDbservice.getAll();
    }

    /**
     * 补码
     *
     * @return
     */
    @Override
    public String repairHairpin(CustomerProductOrderVO order, String productCode, BigDecimal productFinalPrice, UserAccount user, String finishOrderProductNum) {
        SysCompany sysCompany = sysCompanyDbService.selectSysCompanyById(user.getCompanyId());

        Customer customer = customerDbService.selectCustomerById(order.getCustomerId());

        ReturnMoneyVO returnMoney = returnMoneyDbservice.selectReturnMoneyByOrderId(order.getProductOrderId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String da = "";
        if(returnMoney != null) {
            if(returnMoney.getArriveTime() != null) {
                da = sdf.format(returnMoney.getArriveTime());
            }
        }

        CustomerContract contract = contractDbService.selectContractById(order.getContractId());


        String url = "http://api.nsrjlb.com/crm/ExchangeCode/Complement";

        //产品编码 例：67|1,67_11|2（产品编码|产品数量,产品编码|产品数量）
        String req = "code=" + productCode ;

        //到款日期
        if(!StringUtils.isBlank(da)) {
            req += "&fdata=" + da;
        }

        //产品号
        req += "&id=" + finishOrderProductNum;

        //到款金额
        //req += "&price=" + order.getOrderActualTotalAmount();
        if(productFinalPrice != null) {
            req += "&price=" + productFinalPrice;
        }else{
            req += "&price=" + new BigDecimal("0.0");
        }

        //客户名称
        if (!StringUtils.isBlank(customer.getCustomerName())) {
            req += "&firm=" + customer.getCustomerName();
        } else {
            req += "&firm=";
        }

        //公司id
        if (sysCompany != null) {
            req += "&pid=" + sysCompany.getCompanyCode();
        } else {
            req += "&pid=";
        }

        //联系人名称
        if (!StringUtils.isBlank(contract.getContactName())) {
            req += "&contactName=" + contract.getContactName();
        } else {
            req += "&contactName=";
        }

        //手机号
        if (!StringUtils.isBlank(contract.getContactDetails())) {
            req += "&mobile=" + contract.getContactDetails();
        } else {
            req += "&mobile=";
        }

        //订单编号
        req += "&orderNumber=" + order.getOrderNumber();

        //合同开始日期
        req +="&contractStartDate=" + contract.getContractStartDate();

        //支付方式
        if(!StringUtils.isBlank(contract.getPaymentMethod())) {
            req +="&paymentMethod=" + contract.getPaymentMethod();
        }
        String msg = "补码失败";
        log.info("请求数据---"+req);
        String res = post(url, req);
        log.info("返回数据---"+res);
        if (res != null) {
            JSONObject json = JSON.parseObject(res);
            Integer de = json.getInteger("code");
            if (de != null && de == 1) {
                msg = json.getString("msg");
            }
        }
        return msg;
    }

    /**
     * 报表统计 - 业绩分析 - 销售产品分析 - 高级筛选 产品
     * @Author pym
     * @Date  2021/12/29 16:55
     * @param
     * @return {@link {com.crm.model.vo.productManager.ShelfProductsVO}}
     */
    @Override
    public ShelfProductsVO selectShelfProductList() {
        ShelfProductsVO shelfProductsVO = new ShelfProductsVO();
        List<ProductVO> memberShelfProductList = customerMemberProductDbService.selectMemberShelfProductList();
        shelfProductsVO.setMemberShelfProductList(memberShelfProductList);
        List<ProductVO> nonMemberShelfProductList = customerProductDbService.selectNonMemberShelfProductList();
        shelfProductsVO.setNonMemberShelfProductList(nonMemberShelfProductList);
        return shelfProductsVO;
    }
}
